<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Comment;
use app\admin\model\Devicelock;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestoreorder;
use app\admin\model\litestore\Litestoreordergoods;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopbalanceprofit;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopcoupon;
use app\admin\model\Shopdevice;
use app\admin\model\Shopdiscount;
use app\admin\model\Shopdou;
use app\admin\model\Shopmeituan;
use app\admin\model\Shopmno;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptableorder;
use app\admin\model\Shoptuan;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Usercoupon;
use app\admin\model\Userdiscount;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Userscore;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\admin\model\Userweixinmp;
use app\api\service\AirService;
use app\api\service\CfService;
use app\api\service\CurlService;
use app\api\service\DeviceService;
use app\api\service\DouService;
use app\api\service\LockService;
use app\api\service\MeituanService;
use app\api\service\MpService;
use app\api\service\MtService;
use app\api\service\RoomService;
use app\api\service\TableService;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Order extends Api
{
    protected $noNeedLogin = ['wechatNotify', 'checkOrderBookTime', 'sxfOrderCallback', 'checkOrderBookTimeV2', 'checkOrderBookTimeV3', 'checkOrderTip', 'checkOrderTipTest', 'orderInit3', 'initOrderTime'];
    protected $noNeedRight = '*';

    protected $app = null;

    public function _initialize()
    {
        parent::_initialize();

    }


    public function initOrderTime()
    {

        $mac = $this->request->param('mac');

        $key = str_replace(':', '', $mac);
        $obj = $this->redis->get($key);
        $time = "";
        $url = "";

        if ($obj == null || $obj == "" || $obj == false) {

            $shopRoomModel = new Shoproom();
            $room = $shopRoomModel->where('mac', $mac)->find();
            if (!$room) {
                $this->error("包厢暂未关联机顶盒");
            }

            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('room_id', $room['id'])->where('status', 'doing')->order('book_start', 'desc')->find();


            $shopModel = new Shop();
            $shop = $shopModel->where('id', $room['shop_id'])->find();
            $time = "";
            if ($order) {
                $time = date("Y-m-d H:i:s", $order['book_end']);
                $url = cdnurl($shop['qr_code'], true);
                $obj = array();
                $obj['time'] = $time;
                $obj['url'] = $url;
                $this->redis->set($key, json_encode($obj));
            }

        } else {
            $obj = json_decode($obj, true);

            $time = $obj['time'];

            if (strtotime($time) < time()) {
                $time = "";
            }
            if($time == ''){
                $shopRoomModel = new Shoproom();
                $room = $shopRoomModel->where('mac', $mac)->find();


                $shopOrderModel = new Shoporder();
                $order = $shopOrderModel->where('room_id', $room['id'])->where('status', 'doing')->order('book_start', 'desc')->find();
                if ($order) {
                    $time = date("Y-m-d H:i:s", $order['book_end']);
                }
            }
            $url = $obj['url'];


        }
        $ret = array();
        $ret['time'] = $time;
        $ret['url'] = $url;

        if($mac == '28:75:D8:C1:BA:32'){
            //error_log("===testMac===".json_encode($ret));
        }
        $this->success('', $ret);
    }


    public function orderList()
    {

        $page = $this->request->param('page');
        $status = $this->request->param('status');
        $shop_id = $this->request->param('shop_id');
        $user = $this->auth->getUser();


        $limit = 10;
        $offset = ($page - 1) * $limit;

        $orderModel = new Shoporder();
        $where = array();
        $where['user_id'] = $user['id'];
        if ($status != '') {
            $where['status'] = array('=', $status);
        }
        if ($shop_id != "") {
            $where['shop_id'] = $shop_id;
        }
        $list = $orderModel->where($where)->where('status', '<>', 'paying')->order('create_time', 'desc')->where('is_delete', -1)->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {
            $order_no = $val['order_no'];
            $list[$key]['hour'] = ($val['book_end'] - $val['book_start']) / 3600;

            $list[$key]['order_no_str'] = substr($order_no, 0, 5) . "*****" . substr($order_no, strlen($order_no) - 4, 4);
            $list[$key]['book_start'] = date("Y-m-d H:i:s", $val['book_start']);
            $list[$key]['book_end'] = date("Y-m-d H:i:s", $val['book_end']);
            $list[$key]['status_txt'] = $orderModel->formatStatus($val['status']);


        }
        $this->success('', $list);

    }


    public function detail()
    {

        $order_no = $this->request->param("order_no");
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        $order['tuan'] = "";
        if ($order['tuan_id'] != -1) {
            $shopTuanModel = new Shoptuan();
            $tuan = $shopTuanModel->where('id', $order['tuan_id'])->find();
            if ($tuan) {
                $order['tuan'] = $tuan['name'];
            }
        }

        if ($order['coupon_id'] != -1) {
            $userCouponModel = new Usercoupon();
            $coupon = $userCouponModel->where('id', $order['coupon_id'])->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $coupon['coupon_id'])->find();
            $order['coupon'] = $shopCoupon;
        }

        $shopDeviceModel = new Shopdevice();
        $device = $shopDeviceModel->where('room_id', $order['room_id'])->find();
        if ($device['is_bt'] == 1) {
            if ($order['open_code'] == "") {
                //生成蓝牙密码

                $deviceLockModel = new Devicelock();
                $lock = $deviceLockModel->where('room_id', $order['room_id'])->find();
                $lockService = new LockService();
                $param = array();
                $param['startDate'] = date("Y-m-d H:i:s", $order['book_start']);
                $param['endDate'] = date("Y-m-d H:i:s", $order['book_end']);
                $param['lockId'] = $lock['lockId'];
                $password = $lockService->getPassword($param);
                $shopOrderModel->where('id', $order['id'])->update(['open_code' => $password]);
            }
        }
        $order['discount_name'] = "";
        $order['discount_desc'] = "";
        if ($order['discount_id'] > 0) {

            $userDiscountModel = new Userdiscount();
            $shopDiscountModel = new Shopdiscount();

            $userDiscount = $userDiscountModel->where('id', $order['discount_id'])->find();
            $shopDiscount = $shopDiscountModel->where('id', $userDiscount['discount_id'])->find();
            if ($shopDiscount['discount_type'] == '时长抵扣') {
                $order['discount_desc'] = "时长抵扣:" . $shopDiscount['discount_val'] . "小时";
            } else if ($shopDiscount['discount_type'] == '金额抵扣') {
                $order['discount_desc'] = "金额抵扣:" . $shopDiscount['discount_val'] . "元";

            } else {
                $order['discount_desc'] = "折扣抵扣:" . $shopDiscount['discount_val'] . "折";
            }
            $order['discount_name'] = $shopDiscount['name'];

        }

        $order['hour'] = ($order['book_end'] - $order['book_start']) / 3600;
        $order['status_txt'] = $shopOrderModel->formatStatus($order['status']);
        $order['book_start'] = date("Y-m-d H:i:s", $order['book_start']);
        $order['book_end'] = date("Y-m-d H:i:s", $order['book_end']);

        $this->success('', $order);
    }

    public function orderInit()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $shopModel = new \app\admin\model\Shop();
        $room = $shopRoomModel->where('id', $id)->find();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        $startCompareTime = strtotime($date . " " . $start);
        if ($startCompareTime <= time()) {
            $start = date("H:i");
        }


        $time = array();
        $hourArray = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 2; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->order('hour', 'asc')->select();
            foreach ($roomSet as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = $val['amount'];
                }
            }
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);


        $ret = array();
        $ret['name'] = $room['name'];
        $ret['shop_name'] = $shop['name'];
        $ret['status'] = $room['status'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = $balance;

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                // error_log($isWeek."=======".$isTime."========".$isExist);

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;

        $ret['total_price'] = round($totalPrice, 2);

        if ($balance >= $totalPrice) {
            $dis_price = $totalPrice;
            $pay_price = 0;
        } else {
            $dis_price = $balance;
            $pay_price = $totalPrice - $balance;
        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);


        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        $msg = "";
        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;

        $this->success($msg, $ret);

    }


    public function addBookOrder()
    {
        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $setId = $this->request->param('setId');//套餐ID 如果ID 为-1 就是时间预定
        $tuanId = $this->request->param('tuanId');
        $mt_code = $this->request->param('mtCode');
        $orgId = $this->request->param('orgId');
        $dou_code = $this->request->param('douCode');


        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $startTime);
        $day = date("w", $time1);
        if ($day == 0) {
            $day = 7;
        }


        $min = $hour * 60;

        $endStrotime = strtotime("+" . $min . " minute", strtotime($date . " " . $startTime));

        $time2 = $endStrotime;

        $user = $this->auth->getUser();
        $cacheKey = "room_" . $id;
        $cache = $this->redis->get($cacheKey);

        error_log("====ddd===" . $cache);
        if ($cache != "") {
            $cacheObj = $this->redis->get($cacheKey);
            $checkMowTime = strtotime("-60 seconds", time());
            $cache = json_decode($cacheObj, true);
            if ($cache['create_time'] < $checkMowTime) {
                $this->redis->rm($cacheKey);
            }
            $start = $cache['start'];
            $end = $cache['end'];
            if ($cache['user_id'] != $user['id']) {
                $cacheCheck = -1;
                if ($time1 <= $start && $time2 >= $end) $cacheCheck = 1;//全包围
                if ($time1 >= $start && $time2 <= $end) $cacheCheck = 1;//在区间范围内
                if ($time1 <= $end && $time2 > $end) $cacheCheck = 1; //
                if ($time1 < $start && $time2 <= $end && $time2 >= $start) $cacheCheck = 1;
                if ($cacheCheck == 1) $this->error("请稍后提交，前面有客户正在预定");
            }
        }
        $cacheObj = array();
        $cacheObj['user_id'] = $user['id'];
        $cacheObj['start'] = $time1;
        $cacheObj['end'] = $time2;
        $cacheObj['create_time'] = time();
        $this->redis->set($cacheKey, json_encode($cacheObj));


        $isBooked = -1;
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('room_id', $id)->where('status', 'in', ['undo', 'doing'])->order('start_time', 'desc')->select();
        foreach ($bookList as $key => $val) {

            $start = $val['start_time'];
            $end = $val['end_time'];
            if ($time1 <= $start && $time2 >= $end) $isBooked = 1;//全包围
            if ($time1 >= $start && $time2 <= $end) $isBooked = 1;//在区间范围内
            if ($time1 <= $end && $time2 > $end) $isBooked = 1; //
            if ($time1 < $start && $time2 <= $end && $time2 >= $start) $isBooked = 1;

        }
        if ($isBooked == 1) $this->error("此时间段已被预定");

        $shopOrderModel = new Shoporder();
        $user = $this->auth->getUser();

        $checkMowTime = strtotime("-40 seconds", time());
        $isBookIng = -1;
        $checkBookList = $shopOrderModel->where('user_id', "<>", $user['id'])->where('status', 'paying')->where('room_id', $id)->where('create_time', ">=", $checkMowTime)->where('create_time', "<=", time())->select();
        foreach ($checkBookList as $key => $val) {

            $start = $val['book_start'];
            $end = $val['book_end'];

            if ($time1 <= $start && $time2 >= $end) $isBookIng = 1;//全包围
            if ($time1 >= $start && $time2 <= $end) $isBookIng = 1;//在区间范围内
            if ($time1 <= $end && $time2 > $end) $isBookIng = 1; //
            if ($time1 < $start && $time2 <= $end && $time2 >= $start) $isBookIng = 1;
        }
        if ($isBookIng == 1) {
            $this->error("此时间段正在有人预定，请稍后再试");
        }


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();

        if ($orgId == "") {
            $orgId = $shop['org_id'];
        }

        $orderPrice = 0;
        if ($setId == -1) {
            $totalPrice = $hour * $room['hour_price'];
            $orderPrice = $totalPrice;
        } else {
            $shopRoomBookSetModel = new Shoproomset();
            $set = $shopRoomBookSetModel->where('id', $setId)->find();
            $totalPrice = $set['amount'];
            $orderPrice = $totalPrice;
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();
        if ($tuanId != -1 && $mt_code == "" && $dou_code == "") {
            $userTuan = $tuanUserModel->where('user_id', $user['id'])->where('id', $tuanId)->where('status', 'unuse')->order('valid_time', 'asc')->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];
                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $mtService = new MtService();
        $userMtCodeModel = new Usermeituancode();

        if ($mt_code != '') {
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");


                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }

                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }

            }

            //官方校验美团券
            $mtReq = array();
            $mtReq['shop_id'] = $shop['id'];
            $mtReq['code'] = $mt_code;

            $mtInfo = $mtService->couponInfo($mtReq);
            if ($mtInfo['code'] != 200) {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'bad']);
                $this->error("此券不用");
            }
        }

        $douVerifyToken = "";
        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;


                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {


                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $this->error("此券为无效券");
                    }
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }

                } else {
                    $this->error("此券不能可用");
                }
            }

        }


        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;

        if ($totalPrice > 0) {
            if ($balance > 0 && $mt_code == "" && $dou_code == "") {
                $type = "balance";
                if ($balance >= $totalPrice) {
                    $dis_price = $totalPrice;
                    $pay_price = 0;
                } else {
                    $dis_price = $balance;
                    $pay_price = $totalPrice - $balance;
                }

            }
        }

        if ($pay_price < 0) {
            $this->error("金额不对，请再提交一遍");
        }

        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $orderPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $time1;
        $db['book_end'] = $time2;
        $db['set_id'] = $setId;
        $db['tuan_id'] = $tuanId;
        $db['balance'] = $dis_price;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;
        $db['org_id'] = $orgId;

        $db['pay_rate'] = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
        $price = $pay_price - $db['pay_rate'];
        $db['rate'] = formatMoney($shop['ratio'] * $price / 100);


        $code = mt_rand(100000, 999999);
        $db['open_code'] = "";

        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        $this->redis->rm($cacheKey);

        if ($id > 0) {

            if ($mt_code != "") {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'lock']);
            }
            if ($dou_code != "") {

                $userDouCodeModel->where('dou_code', $dou_code)->update(['status' => 'lock', 'order_id' => $id]);
            }

            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定" . $hour . "小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/order/sxfOrderCallback";

                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();
                $req['mno'] = $org['mno'];//纷享未来药房
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = "包厢预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                //error_log("====req==".json_encode($req));

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }
            } else {

                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                if ($tuanId != -1) {
                    $tuanUserModel->where('id', $tuanId)->update(['status' => 'used']);
                }

                $order = $shopOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    $isChecked = $mtService->syncMt($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                }

                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");


                    $douData = $userDouCodeModel->where('dou_code', $dou_code)->find();
                    if ($douData) {
                        $shopDouModel = new Shopdou();
                        $shopDou = $shopDouModel->where('sku_id', $douData['sku_id'])->find();
                        if ($shopDou) {
                            $shopOrderModel->where('id', $order['id'])->update(['amount' => $shopDou['price']]);
                        }
                    }


                }

                $this->redis->set($order['shop_id'], time());
                $roomService = new RoomService();
                $roomService->addBookData($order);
                $shopOrderModel->where('id', $id)->update(['status' => 'payed', 'update_time' => time()]);


                $mpService = new MpService();
                $mpWxModel = new Userweixinmp();
                $shopModel = new \app\admin\model\Shop();
                $shop = $shopModel->where('id', $order['shop_id'])->find();
                $wx = $mpWxModel->where('mobile', $shop['mobile'])->find();
                if ($wx) {


                    $userModel = new \app\admin\model\User();
                    $user = $userModel->where('id', $order['user_id'])->find();
                    $msg = array();
                    $msg['openid'] = $wx['openid'];
                    $msg['room'] = $order['room_name'];
                    $msg['amount'] = $order['amount'];
                    $msg['phone'] = $user['mobile'];
                    $msg['time'] = date("Y-m-d H:i", $order['book_start']);
                    $msg['endTime'] = date("Y-m-d H:i", $order['book_end']);


                    $mpService->addOrderNotify($this->wxApp, $msg);


                }

            }


            if ($type == "balance") {

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                    'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
            }


            $this->success('下单成功', $info);
        } else {
            $this->error("订单生成失败,请联系客服");
        }

    }


    public function addBookOrderFz()
    {
        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $setId = $this->request->param('setId');//套餐ID 如果ID 为-1 就是时间预定
        $tuanId = $this->request->param('tuanId');
        $mt_code = $this->request->param('mtCode');
        $orgId = $this->request->param('orgId');
        $dou_code = $this->request->param('douCode');


        /**
         * 判断是和已预定的时间冲突
         */

        $time1 = strtotime($date . " " . $startTime);
        $day = date("w", $time1);
        if ($day == 0) {
            $day = 7;
        }


        $min = $hour * 60;

        $endStrotime = strtotime("+" . $min . " minute", strtotime($date . " " . $startTime));

        $time2 = $endStrotime;

        $shopRoomBookModel = new Shoproombook();

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time2)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->where("end_time", "<=", $time2)->find();
        $checkEnd4 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null || $checkEnd4 != null) {
            $this->error("此时间段已被预定");
        }

        $shopOrderModel = new Shoporder();
        $user = $this->auth->getUser();

        $checkStart2 = $shopOrderModel->where('user_id', "<>", $user['id'])->where('status', 'paying')->where('room_id', $id)->where('book_start', "<=", $time1)->where("book_end", ">=", $time2)->order('create_time', 'desc')->find();

        $checkMowTime = strtotime("-20 seconds", time());
        $isBookIng = -1;
        if ($checkStart2 && $checkStart2['create_time'] > $checkMowTime) {

            $isBookIng = 1;

        }
        if ($isBookIng == -1) {
            $checkEnd2 = $shopOrderModel->where('user_id', "<>", $user['id'])->where('status', 'paying')->where('room_id', $id)->where('book_start', ">=", $time1)->where('book_start', "<=", $time2)->where("book_end", ">=", $time2)->order('create_time', 'desc')->find();
            if ($checkEnd2 && $checkEnd2['create_time'] > $checkMowTime) {
                $isBookIng = 1;
            }
        }

        if ($isBookIng == -1) {
            $checkEnd32 = $shopOrderModel->where('user_id', "<>", $user['id'])->where('status', 'paying')->where('room_id', $id)->where('book_start', "<=", $time1)->where('book_end', ">=", $time1)->where("book_end", "<=", $time2)->order('create_time', 'desc')->find();
            if ($checkEnd32 && $checkEnd32['create_time'] > $checkMowTime) {
                $isBookIng = 1;
            }
        }

        if ($isBookIng == 1) {
            $this->error("此时间段正在有人预定，请稍后再试");
        }


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();

        if ($orgId == "") {
            $orgId = $shop['org_id'];
        }

        $orderPrice = 0;
        if ($setId == -1) {
            $totalPrice = $hour * $room['hour_price'];
            $orderPrice = $totalPrice;
        } else {
            $shopRoomBookSetModel = new Shoproomset();
            $set = $shopRoomBookSetModel->where('id', $setId)->find();
            $totalPrice = $set['amount'];
            $orderPrice = $totalPrice;
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();
        if ($tuanId != -1 && $mt_code == "" && $dou_code == "") {
            $userTuan = $tuanUserModel->where('user_id', $user['id'])->where('id', $tuanId)->where('status', 'unuse')->order('valid_time', 'asc')->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];
                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $mtService = new MtService();
        $userMtCodeModel = new Usermeituancode();

        if ($mt_code != '') {
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");


                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                if ($endTime < $startTime) {
                    $endTime = strtotime(date("Y-m-d", strtotime("+1 day", $startTime)) . " " . $end);

                }

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }

                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }

            }

            //官方校验美团券
            $mtReq = array();
            $mtReq['shop_id'] = $shop['id'];
            $mtReq['code'] = $mt_code;

            $mtInfo = $mtService->couponInfo($mtReq);
            if ($mtInfo['code'] != 200) {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'bad']);
                $this->error("此券不可用");
            }
        }

        $douVerifyToken = "";
        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                if ($endTime < $startTime) {
                    $endTime = strtotime(date("Y-m-d", strtotime("+1 day", $startTime)) . " " . $end);
                }

                $isTime = false;


                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {


                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $this->error("此券为无效券");
                    }
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }

                } else {
                    $this->error("此券不可用2");
                }
            }

        }


        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;

        if ($totalPrice > 0) {
            if ($balance > 0 && $mt_code == "" && $dou_code == "") {
                $type = "balance";
                if ($balance >= $totalPrice) {
                    $dis_price = $totalPrice;
                    $pay_price = 0;
                } else {
                    $dis_price = $balance;
                    $pay_price = $totalPrice - $balance;
                }

            }
        }

        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $orderPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $time1;
        $db['book_end'] = $time2;
        $db['set_id'] = $setId;
        $db['tuan_id'] = $tuanId;
        $db['balance'] = $dis_price;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;
        $db['org_id'] = $orgId;
        $db['pay_rate'] = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
        $price = $pay_price - $db['pay_rate'];
        $db['rate'] = formatMoney($shop['ratio'] * $price / 100);


        $code = mt_rand(100000, 999999);
        $db['open_code'] = "";

        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        if ($id > 0) {

            if ($mt_code != "") {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'lock']);
            }
            if ($dou_code != "") {

                $userDouCodeModel->where('dou_code', $dou_code)->update(['status' => 'lock', 'order_id' => $id]);
            }

            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定" . $hour . "小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/order/sxfOrderCallback";

                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();

                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
                $mno = $org['mno'];
                if ($shopMno) {
                    if ($shopMno['ratio'] == 100) {
                        //走挂靠
                        $mno = $shopMno['mno'];
                    } else {
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

                        $realPay = formatMoney($pay_price - $pay_price * 0.006);
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }

                //error_log("===mno=".$mno);
                $req['mno'] = $mno;
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = "包厢预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                //error_log("===res=js api==".json_encode($res));
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }
            } else {

                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                if ($tuanId != -1) {
                    $tuanUserModel->where('id', $tuanId)->update(['status' => 'used']);
                }

                $order = $shopOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    $isChecked = $mtService->syncMt($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                }

                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                }

                $this->redis->set($order['shop_id'], time());
                $roomService = new RoomService();
                $roomService->addBookData($order);
                $shopOrderModel->where('id', $id)->update(['status' => 'payed', 'update_time' => time()]);


                $mpService = new MpService();
                $mpWxModel = new Userweixinmp();
                $shopModel = new \app\admin\model\Shop();
                $shop = $shopModel->where('id', $order['shop_id'])->find();
                $wx = $mpWxModel->where('mobile', $shop['mobile'])->find();
                if ($wx) {


                    $userModel = new \app\admin\model\User();
                    $user = $userModel->where('id', $order['user_id'])->find();
                    $msg = array();
                    $msg['openid'] = $wx['openid'];
                    $msg['room'] = $order['room_name'];
                    $msg['amount'] = $order['amount'];
                    $msg['phone'] = $user['mobile'];
                    $msg['time'] = date("Y-m-d H:i", $order['book_start']);
                    $msg['endTime'] = date("Y-m-d H:i", $order['book_end']);


                    $mpService->addOrderNotify($this->wxApp, $msg);


                }

            }


            if ($type == "balance") {

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                    'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
            }


            $this->success('下单成功', $info);
        } else {
            $this->error("订单生成失败,请联系客服");
        }

    }


    public function addBookOrderFzMore()
    {
        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $setId = $this->request->param('setId');//套餐ID 如果ID 为-1 就是时间预定
        $tuanId = $this->request->param('tuanId');
        $mt_code = $this->request->param('mtCode');
        $orgId = $this->request->param('orgId');
        $dou_code = $this->request->param('douCode');


        /**
         * 判断是和已预定的时间冲突
         */

        $time1 = strtotime($date . " " . $startTime);
        $day = date("w", $time1);
        if ($day == 0) {
            $day = 7;
        }


        $min = $hour * 60;

        $endStrotime = strtotime("+" . $min . " minute", strtotime($date . " " . $startTime));

        $time2 = $endStrotime;


        $cacheKey = "room_" . $id;
        $cache = $this->redis->get($cacheKey);
        $user = $this->auth->getUser();
        if ($cache != "") {
            $cacheObj = $this->redis->get($cacheKey);
            $checkMowTime = strtotime("-60 seconds", time());
            $cache = json_decode($cacheObj, true);
            if ($cache['create_time'] < $checkMowTime) {
                $this->redis->rm($cacheKey);
            }
            $start = $cache['start'];
            $end = $cache['end'];
            if ($cache['user_id'] != $user['id']) {
                $cacheCheck = -1;
                if ($time1 <= $start && $time2 >= $end) $cacheCheck = 1;//全包围
                if ($time1 >= $start && $time2 <= $end) $cacheCheck = 1;//在区间范围内
                if ($time1 <= $end && $time2 > $end) $cacheCheck = 1; //
                if ($time1 < $start && $time2 <= $end && $time2 >= $start) $cacheCheck = 1;
                if ($cacheCheck == 1) $this->error("请稍后提交，前面有客户正在预定");
            }
        }
        $cacheObj = array();
        $cacheObj['user_id'] = $user['id'];
        $cacheObj['start'] = $time1;
        $cacheObj['end'] = $time2;
        $cacheObj['create_time'] = time();
        $this->redis->set($cacheKey, json_encode($cacheObj));


        $isBooked = -1;
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('room_id', $id)->where('status', 'in', ['undo', 'doing'])->order('start_time', 'desc')->select();
        foreach ($bookList as $key => $val) {

            $start = $val['start_time'];
            $end = $val['end_time'];
            if ($time1 <= $start && $time2 >= $end) $isBooked = 1;//全包围
            if ($time1 >= $start && $time2 <= $end) $isBooked = 1;//在区间范围内
            if ($time1 <= $end && $time2 > $end) $isBooked = 1; //
            if ($time1 < $start && $time2 <= $end && $time2 >= $start) $isBooked = 1;

        }
        if ($isBooked == 1) $this->error("此时间段已被预定");


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();

        if ($orgId == "") {
            $orgId = $shop['org_id'];
        }

        $orderPrice = 0;
        if ($setId == -1) {
            $totalPrice = $hour * $room['hour_price'];
            $orderPrice = $totalPrice;
        } else {
            $shopRoomBookSetModel = new Shoproomset();
            $set = $shopRoomBookSetModel->where('id', $setId)->find();
            $totalPrice = $set['amount'];
            $orderPrice = $totalPrice;
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();
        if ($tuanId != -1 && $mt_code == "" && $dou_code == "") {
            $userTuan = $tuanUserModel->where('user_id', $user['id'])->where('id', $tuanId)->where('status', 'unuse')->order('valid_time', 'asc')->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];
                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $mtService = new MtService();
        $userMtCodeModel = new Usermeituancode();

        if ($mt_code != '') {
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");


                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }

                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }

            }

            //官方校验美团券
            $mtReq = array();
            $mtReq['shop_id'] = $shop['id'];
            $mtReq['code'] = $mt_code;

            $mtInfo = $mtService->couponInfo($mtReq);
            if ($mtInfo['code'] != 200) {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'bad']);
                $this->error("此券不用");
            }
        }

        $douVerifyToken = "";
        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;


                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {


                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $this->error("此券为无效券");
                    }
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }

                } else {
                    $this->error("此券不能可用");
                }
            }

        }


        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;

        if ($totalPrice > 0) {
            if ($balance > 0 && $mt_code == "" && $dou_code == "") {
                $type = "balance";
                if ($balance >= $totalPrice) {
                    $dis_price = $totalPrice;
                    $pay_price = 0;
                } else {
                    $dis_price = $balance;
                    $pay_price = $totalPrice - $balance;
                }

            }
        }

        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $orderPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $time1;
        $db['book_end'] = $time2;
        $db['set_id'] = $setId;
        $db['tuan_id'] = $tuanId;
        $db['balance'] = $dis_price;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;
        $db['org_id'] = $orgId;
        $db['pay_rate'] = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
        $price = $pay_price - $db['pay_rate'];
        $db['rate'] = formatMoney($shop['ratio'] * $price / 100);


        $code = mt_rand(100000, 999999);
        $db['open_code'] = "";

        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        $this->redis->rm($cacheKey);

        if ($id > 0) {

            if ($mt_code != "") {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'lock']);
            }
            if ($dou_code != "") {

                $userDouCodeModel->where('dou_code', $dou_code)->update(['status' => 'lock', 'order_id' => $id]);
            }

            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定" . $hour . "小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/order/sxfOrderCallback";

                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();

                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
                $mno = $org['mno'];
                if ($shopMno) {


                    if ($shopMno['ratio'] == 100) {
                        //走挂靠
                        $mno = $shopMno['mno'];
                    } else {


                        $listMnos = $shopMnoModel->where('shop_id', $shop['id'])->select();
                        $fs = array();
                        $realPay = formatMoney($pay_price - $pay_price * 0.006);
                        foreach ($listMnos as $key => $val) {
                            //走分账
                            $fusruleId = array();
                            $fusruleId['mno'] = $val['mno'];
                            $fusruleId['allotValue'] = formatMoney($val['ratio'] * $realPay / 100);
                            $fs[] = $fusruleId;

                        }

                        $req['fusruleId'] = $fs;
                    }
                }

                $req['mno'] = $mno;
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = "包厢预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);

                error_log("===fz==" . $res);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }
            } else {

                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                if ($tuanId != -1) {
                    $tuanUserModel->where('id', $tuanId)->update(['status' => 'used']);
                }

                $order = $shopOrderModel->where('id', $id)->find();

                if ($mt_code != "") {

                    if ($shop['mt2_token'] != "") {
                        $meituanService = new MeituanService();
                        $isChecked = $meituanService->consume($order);
                    } else {
                        $isChecked = $mtService->syncMt($order);

                    }

                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                }

                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                }

                $this->redis->set($order['shop_id'], time());
                $roomService = new RoomService();
                $roomService->addBookData($order);
                $shopOrderModel->where('id', $id)->update(['status' => 'payed', 'update_time' => time()]);


                $mpService = new MpService();
                $mpWxModel = new Userweixinmp();
                $shopModel = new \app\admin\model\Shop();
                $shop = $shopModel->where('id', $order['shop_id'])->find();
                $wx = $mpWxModel->where('mobile', $shop['mobile'])->find();
                if ($wx) {


                    $userModel = new \app\admin\model\User();
                    $user = $userModel->where('id', $order['user_id'])->find();
                    $msg = array();
                    $msg['openid'] = $wx['openid'];
                    $msg['room'] = $order['room_name'];
                    $msg['amount'] = $order['amount'];
                    $msg['phone'] = $user['mobile'];
                    $msg['time'] = date("Y-m-d H:i", $order['book_start']);
                    $msg['endTime'] = date("Y-m-d H:i", $order['book_end']);


                    $mpService->addOrderNotify($this->wxApp, $msg);


                }

            }


            if ($type == "balance") {

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                    'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
            }


            $this->success('下单成功', $info);
        } else {
            $this->error("订单生成失败,请联系客服");
        }

    }


    public function restore()
    {
        $user = $this->auth->getUser();
        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $userBalanceModel = new Userbalance();
        $userTuanModel = new Usertuan();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order) {
            if ($order['user_id'] != $user['id']) {
                $this->error("无权限操作");
            }
            if ($order['status'] == 'paying') {
                $b = $userBalanceModel->where('user_id', $user['id'])->where('type', 'out')->where('order_id', $order['id'])->find();
                if ($b) {
                    if ($order['tuan_id'] != -1) {
                        $tuan = $userTuanModel->where('id', $order['tuan_id'])->find();
                        if ($tuan) {
                            $userTuanModel->where('id', $tuan['id'])->update(['status' => 'unuse']);
                        }
                    }

                    if ($order['coupon_id'] != -1) {
                        $userCouponModel = new Usercoupon();
                        $coupon = $userCouponModel->where('id', $order['coupon_id'])->find();
                        if ($coupon) {
                            $userCouponModel->where('id', $coupon['id'])->update(['status' => 'unuse']);
                        }
                    }

                    if ($order['mt_code'] != "") {
                        $userMtModel = new Usermeituancode();
                        $userMtModel->where('mt_code', $order['mt_code'])->update(['status' => 'unuse']);

                    }


                    if ($order['dou_code'] != "") {
                        $userDouModel = new Userdoucode();
                        $userDouModel->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);

                    }
                    $userBalanceModel->where('id', $b['id'])->delete();
                    $this->success('');
                } else {
                    $this->success('');
                }
            } else {
                $this->error("订单不允许");
            }
        } else {
            $this->error("订单不存在");
        }
    }

    public function sxfOrderCallback()
    {
        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'payed', 'update_time' => time()]);

            if ($order['discount_id'] > 0) {
                $userDiscountModel = new Userdiscount();
                $userDiscountModel->where('id', $order['discount_id'])->update(['status' => 2]);
            }
            $roomService = new RoomService();
            $roomService->addBookData($order);

            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();

            /**
             * 商家分润
             */
            $pay_price = $order['pay_amount'];
            $pay_rate = formatMoney($pay_price * 0.006);
            $shopProfit = $pay_price - formatMoney($shop['ratio'] * $pay_price / 100) - $pay_rate;

            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => $shopProfit]);

            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();



                $userModel = new \app\admin\model\User();
                $agentUser = $userModel->where('id', $shop['agent_id'])->find();
                $tmpRatio = 0;
                if ($agentUser['ref_uid'] != -1) {

                    $refRatio =$shop['agent_ratio']- $agentUser['ratio'] ;
                    $tmpRatio =  $agentUser['ratio'] ;
                    if ($refRatio > 0) {
                        $refFee = $refRatio * $order['pay_amount'] / 100;
                        if ($refFee > 0) {
                            $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                'user_id' => $agentUser['ref_uid'], 'create_time' => time(), 'amount' => formatMoney($refFee), 'flag' => 'team']);
                        }
                    }
                }

                $agentFee = ($shop['agent_ratio']-$tmpRatio) * $order['pay_amount'] / 100;

                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }

            }

            $this->redis->set($order['shop_id'], time());
            if ($order['tuan_id'] != -1) {
                $tuanUserModel = new Usertuan();
                $tuanUserModel->where('id', $order['tuan_id'])->update(['status' => 'used']);

            }

            if ($order['coupon_id'] != -1) {
                $userCouponModel = new Usercoupon();
                $userCouponModel->where('id', $order['coupon_id'])->update(['status' => 'used']);
            }
            if ($order['mt_code'] != "") {
                $mtService = new MtService();
                $mtService->syncMt($order);
            }
            if ($order['dou_code'] != "") {
                $douService = new DouService();
                $douService->verifyCode($order);
                //$userDouModel->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);
            }

            $userScore = new Userscore();
            $userScore->insert(['user_id' => $order['user_id'], 'score' => $order['amount'], 'mark' => $order['shop_name'] . "-" . $order['room_name'] . '消费' . $order['amount'], 'create_time' => time(), 'order_id' => $order['id'], 'shop_id' => $order['shop_id']]);

            $mpService = new MpService();
            $mpWxModel = new Userweixinmp();
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();
            $wx = $mpWxModel->where('user_id', $shop['user_id'])->find();
            if ($wx) {


                $userModel = new \app\admin\model\User();
                $user = $userModel->where('id', $order['user_id'])->find();
                $msg = array();
                $msg['openid'] = $wx['openid'];
                $msg['order_no'] = $order['order_no'];
                $msg['shop_name'] = $order['shop_name'];
                $msg['room_name'] = $order['room_name'];
                $msg['amount'] = $order['amount'];
                $msg['mobile'] = $user['mobile'];
                $msg['book_start'] = date("Y-m-d H:i", $order['book_start']);

                $mpService->addOrderNotify($this->wxApp, $msg);


            }


            if ($order['balance_type'] == 4) {

                $userBalanceModel = new Userbalance();
                $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                if ($balance <= 0) $balance = 0;
                if ($balance > 0) {
                    $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out',
                        'amount' => $balance, 'mark' => $order['shop_name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id']]);
                }

                if ($shop['is_join_balance'] == 1) {
                    $userAllBalanceModel = new Userallbalance();
                    $orderBalance = $order['balance'];

                    $orderAllBalance = $orderBalance - $balance;

                    $ratioList = $userAllBalanceModel->cacBalance($order['user_id'], $orderAllBalance);
                    $shopProfit = 0;
                    foreach ($ratioList as $key => $val) {
                        $shopProfit += $val['amount'] / $val['ratio'];
                        $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'out', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'order', 'order_id' => $order['id'], 'order_type' => 'qp']);
                    }
                    //划拨平台利润给店铺
                    $shopMoney = $shopProfit - $shopProfit * 0.006 - $shopProfit * $shop['ratio'] / 100;
                    $shopBalanceProfitModel = new Shopbalanceprofit();
                    $shopBalanceProfitModel->insert(['shop_id' => $shop['id'], 'order_id' => $order['id'], 'create_time' => time(), 'amount' => $shopMoney]);

                }

            }

        }
    }

    public function wechatNotify()
    {

        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee'] / 100;


        if (in_array($result['return_code'], ['SUCCESS'])) {

            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'payed', 'update_time' => time()]);


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();

            /**
             * 商家分润
             */
            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['pay_amount'] - $order['rate'] - $order['pay_rate']))]);

            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();

                $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;

                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }

            }


            $this->redis->set($order['shop_id'], time());


            $roomService = new RoomService();
            $roomService->addBookData($order);


            if ($order['tuan_id'] != -1) {
                $tuanUserModel = new Usertuan();
                $tuanUserModel->where('id', $order['tuan_id'])->update(['status' => 'used']);

            }
            if ($order['mt_code'] != "") {
                $mtService = new MtService();
                $mtService->syncMt($order);
            }

            if ($order['dou_code'] != "") {
                $userDouModel = new Userdoucode();
                $userDouModel->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);

            }


        }
        return $pay->success();
    }


    public function checkOrderBookTime()
    {

        $date = $this->request->param('date');
        $hour = $this->request->param('hour');
        $bookStart = $this->request->param('starTime');
        $room_id = $this->request->param('room_id');

        $bookStartTime = strtotime($date . " " . $bookStart);
        $bookEndTime = strtotime("+" . $hour * 60 . " minute", strtotime($date . " " . $bookStart));

        $dateTime = strtotime($date);

        $ret = array();
        $oneTime = strtotime("+1 day", $dateTime);
        $date2 = date("Y-m-d", $oneTime);


        $oneInitStart = $date . " 00:00";
        $oneInitStart2 = date("Y-m-d", $oneTime) . " 00:00";

        $shopBookTime = new Shoproombook();
        $bookList = $shopBookTime->where('room_id', $room_id)->where('status', "<>", 'done')->select();

        $oneList = array();
        $ret = array();
        $twoList = array();
        for ($i = 0; $i <= 23; $i++) {

            $obj = array();
            $obj['isFree'] = true;
            $obj['isNow'] = false;
            $obj['index'] = $i;

            $obj2 = array();
            $obj2['isFree'] = true;
            $obj2['isNow'] = false;
            $obj2['index'] = $i;
            $startTime = strtotime("+" . $i . " hour", strtotime($oneInitStart));
            if ($i != 23) {
                $endTime = strtotime("+" . ($i + 1) . " hour", strtotime($oneInitStart));
            } else {
                $endTime = strtotime($date . " 23:59:59");
            }

            $startTime2 = strtotime("+" . $i . " hour", strtotime($oneInitStart2));
            if ($i != 23) {
                $endTime2 = strtotime("+" . ($i + 1) . " hour", strtotime($oneInitStart2));
            } else {
                $endTime2 = strtotime($date2 . " 23:59:59");
            }

            foreach ($bookList as $k => $v) {
                if (($startTime >= $v['start_time'] && $endTime <= $v['end_time']) || ($v['end_time'] >= $startTime && $v['end_time'] <= $endTime) || ($v['start_time'] >= $startTime && $v['start_time'] <= $endTime)) {
                    $obj['isFree'] = false;
                }

                if (($startTime2 >= $v['start_time'] && $endTime2 <= $v['end_time']) || ($v['end_time'] >= $startTime2 && $v['end_time'] <= $endTime2) || ($v['start_time'] >= $startTime2 && $v['start_time'] <= $endTime2)) {
                    $obj2['isFree'] = false;
                }
            }

            if (($startTime >= $bookStartTime && $endTime <= $bookEndTime) || ($bookEndTime > $startTime && $bookEndTime <= $endTime) || ($bookStartTime > $startTime && $bookStartTime <= $endTime)) {
                if ($obj['isFree'] == true) {
                    $obj['isNow'] = true;
                }

            }

            if (($startTime2 >= $bookStartTime && $endTime2 <= $bookEndTime) || ($bookEndTime >= $startTime2 && $bookEndTime <= $endTime2) || ($bookStartTime >= $startTime2 && $bookStartTime <= $endTime2)) {
                if ($obj2['isFree'] == true) {
                    $obj2['isNow'] = true;
                }
            }
            $oneList[] = $obj;
            $twoList[] = $obj2;

        }
        $ret['list'] = $oneList;
        $ret['date'] = $date;
        $ret['date2'] = date("Y-m-d", $oneTime);
        $ret['list2'] = $twoList;


        $this->success('', $ret);
    }


    public function checkOrderBookTimeV2()
    {

        $date = $this->request->param('date');
        $hour = $this->request->param('hour');
        $bookStart = $this->request->param('starTime');
        $room_id = $this->request->param('room_id');

        $bookStartTime = strtotime($date . " " . $bookStart);
        $bookEndTime = strtotime("+" . $hour * 60 . " minute", strtotime($date . " " . $bookStart));

        $shopBookTime = new Shoproombook();
        $bookList = $shopBookTime->where('room_id', $room_id)->where('status', "<>", 'done')->select();

        $ret = array();

        $currentDate = date("Y-m-d");
        if ($currentDate != $date) {
            $time = getHourSlot2($date);
        } else {
            $time = getHourSlot();
        }
        foreach ($time as $k => $v) {
            $startDate = $v['time'] . ":00";
            $startDate2 = $v['time'] . ":30";

            $startTime = strtotime($startDate);
            $startTime2 = strtotime($startDate2);

            $time[$k]['isBook'] = false;
            $time[$k]['isSelect'] = false;
            $time[$k]['isHalf'] = false;


            $hstart1 = date("H", $startTime2);
            $mstart1 = date("i", $startTime2);
            $mDate1 = date("Y-m-d", $startTime2);


            if ($startTime >= $bookStartTime && $startTime <= $bookEndTime) {
                $time[$k]['isSelect'] = true;
            }
            if ($startTime2 >= $bookStartTime && $startTime2 <= $bookEndTime) {
                $time[$k]['isSelect'] = true;
            }

            $hstart_1 = date("H", $bookStartTime);
            $mstart_1 = date("i", $bookStartTime);
            $mDate_1 = date("Y-m-d", $bookStartTime);

            $hstart_2 = date("H", $bookEndTime);
            $mstart_2 = date("i", $bookEndTime);

            if ($hstart_2 == $hstart1 && $mstart_2 < 30) {
                $time[$k]['isHalf'] = true;
            }

            foreach ($bookList as $k1 => $v1) {


                if ($startTime >= $v1['start_time'] && $startTime <= $v1['end_time']) {
                    $time[$k]['isBook'] = true;
                    $isFree = false;
                }
                if ($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']) {
                    $time[$k]['isBook'] = true;
                    $isFree = false;
                }

            }

        }
        $ret['list'] = $time;
        $ret['date'] = $date;


        $this->success('', $ret);
    }


    public function checkOrderBookTimeV3()
    {

        $date = $this->request->param('date');
        $hour = $this->request->param('hour');
        $bookStart = $this->request->param('starTime');
        $room_id = $this->request->param('room_id');

        $bookStartTime = strtotime($date . " " . $bookStart);
        $bookEndTime = strtotime("+" . $hour * 60 . " minute", strtotime($date . " " . $bookStart));

        $shopBookTime = new Shoproombook();
        $bookList = $shopBookTime->where('room_id', $room_id)->where('status', "<>", 'done')->select();

        $ret = array();


        $currentDate = date("Y-m-d");
        if ($currentDate != $date) {
            $time = getHourSlot2($date);
        } else {
            $time = getHourSlot();

        }

        error_log("====time==" . json_encode($time));
        foreach ($time as $k => $v) {
            $startDate = $v['time'] . ":00";
            $startDate2 = $v['time'] . ":30";

            $startTime = strtotime($startDate);
            $startTime2 = strtotime($startDate2);

            $time[$k]['isBook'] = false;
            $time[$k]['isSelect'] = false;


            if ($startTime >= $bookStartTime && $startTime <= $bookEndTime) {
                $time[$k]['isSelect'] = true;
            }
            if ($startTime2 >= $bookStartTime && $startTime2 <= $bookEndTime) {
                $time[$k]['isSelect'] = true;
            }

            foreach ($bookList as $k1 => $v1) {


                if ($startTime >= $v1['start_time'] && $startTime <= $v1['end_time']) {
                    $time[$k]['isBook'] = true;
                    $isFree = false;
                }
                if ($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']) {
                    $time[$k]['isBook'] = true;
                    $isFree = false;
                }
            }

        }
        $ret['list'] = $time;
        $ret['date'] = $date;


        $this->success('', $ret);
    }

    public function refund()
    {

        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] != "payed") {
            $this->error("此订单状态不允许退款");
        }

        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();
        $hour = $org['refund_hour'];
        $time = strtotime("+" . $hour . " hour", time());
        if ($time >= $order['book_start']) {
            $this->error("离开始只有" . $hour . "个小时，不允许退款");
        }
        $amount = $order['pay_amount'];

        $shopModel = new \app\admin\model\Shop();

        $shop = $shopModel->where('id', $order['shop_id'])->find();
        if ($order['balance'] >= $amount) {
            $refundAmount = 0;
            $backBalanceAmount = $amount;
        } else {
            $refundAmount = $amount - $order['balance'];
            $backBalanceAmount = $order['balance'];
        }

        if ($order['pay_amount'] > 0 && $refundAmount > 0) {


            $refundOrder_no = getOrderSn();

            $orgModel = new Org();
            $org = $orgModel->where('id', $order['org_id'])->find();
            $mno = $org['mno'];

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
            if ($shopMno && $shopMno['ratio'] == 100) {
                $mno = $shopMno['mno'];
            }

            $req = array();
            $req['mno'] = $mno;
            $req['ordNo'] = $refundOrder_no;
            $req['origOrderNo'] = $order['order_no'];
            $req['amt'] = $refundAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            $result = json_decode($ret, true);
            if ($result['respData']['bizCode'] != "0000") {
                $this->error($result['respData']['bizMsg']);
            }
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'refund_order_no' => $refundOrder_no, 'update_time' => time()]);
        } else {
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);
        }
        //退余额
        if ($order['balance'] > 0) {
            $userBalanceModel = new Userbalance();
            $balanceDb = $userBalanceModel->where('user_id', $order['user_id'])->where('order_id', $order['id'])->where('type', 'out')->find();
            $userBalanceModel->insert(['user_id' => $balanceDb['user_id'], 'type' => 'in', 'amount' => $balanceDb['amount'], 'mark' => '订单退款', 'create_time' => time(),
                'shop_id' => $balanceDb['shop_id'], 'order_id' => $balanceDb['order_id'], 'b_type' => 'refund']);
        }
        //退商家分润 ，代理商分润
        if ($order['pay_amount'] > 0) {
            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->where('order_id', $order['id'])->where('user_id', $shop['user_id'])->delete();

            $userOrderProfitModel = new Userorderprofit();
            $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->delete();
        }

        //团购券
        if ($order['tuan_id'] != -1) {
            $userTuanModel = new Usertuan();
            $userTuanModel->where('order_id', $order['id'])->update(['status' => 'unuse']);
        }

        //恢复预定
        $roomBookOrderModel = new Shoproombook();
        $roomBookOrderModel->where('order_id', $order['id'])->delete();

        $cleanRoomModel = new Roomclean();
        $cleanRoomModel->where('order_id', $order['id'])->delete();


        $this->success('退款成功');


    }


    // 1小时内退款 就扣15%
    public function refundV2()
    {

        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] != "payed") {
            $this->error("此订单状态不允许退款");
        }


        $time = strtotime("+1 hour", time());
        $fiveMintue = strtotime("-5 minute", time());


        $amount = $order['amount'];

        $shopModel = new \app\admin\model\Shop();

        $shop = $shopModel->where('id', $order['shop_id'])->find();
        $isRefundAll = 0;//是否退15%
        if ($order['balance'] >= $amount) {
            $refundAmount = 0;
        } else {
            $refundAmount = $amount - $order['balance'];
            if ($order['create_time'] >= $fiveMintue) {
                $refundAmount = $refundAmount;
            } else {
                if ($time >= $order['book_start']) {
                    $isRefundAll = $refundAmount * 0.15 * 100;
                    $isRefundAll = ceil($isRefundAll) / 100;
                    $refundAmount = $refundAmount - $isRefundAll;
                }
            }

        }

        //退实付金额
        if ($order['pay_amount'] > 0 && $refundAmount > 0) {

            $refundOrder_no = getOrderSn();

            $orgModel = new Org();
            $org = $orgModel->where('id', $order['org_id'])->find();
            $mno = $org['mno'];

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
            if ($shopMno && $shopMno['ratio'] == 100) {
                $mno = $shopMno['mno'];
            }

            $req = array();
            $req['mno'] = $mno;
            $req['ordNo'] = $refundOrder_no;
            $req['origOrderNo'] = $order['order_no'];
            $req['amt'] = $refundAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);

            error_log(json_encode($req) . "===v2 refund==" . $ret);
            $result = json_decode($ret, true);

            if ($result['respData']['bizCode'] != "0000") {
                $this->error($result['respData']['bizMsg']);
            }
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'refund_order_no' => $refundOrder_no, 'update_time' => time()]);
        } else {
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);
        }

        //退余额
        if ($order['balance'] > 0) {
            $userBalanceModel = new Userbalance();
            $balanceDb = $userBalanceModel->where('user_id', $order['user_id'])->where('order_id', $order['id'])->where('type', 'out')->find();
            $b = $balanceDb['amount'];
            if ($time >= $order['book_start']) {
                $b = $balanceDb['amount'] - $balanceDb['amount'] * 0.15;
            }
            $userBalanceModel->insert(['user_id' => $balanceDb['user_id'], 'type' => 'in', 'amount' => $b, 'mark' => '订单退款', 'create_time' => time(),
                'shop_id' => $balanceDb['shop_id'], 'order_id' => $balanceDb['order_id'], 'b_type' => 'refund']);
        }

        //退商家分润 ，代理商分润
        if ($order['pay_amount'] > 0) {
            $shopOrderProfitModel = new Shoporderprofit();
            if ($isRefundAll > 0) {
                $orderProfit = $shopOrderProfitModel->where('order_id', $order['id'])->where('user_id', $shop['user_id'])->find();
                if ($orderProfit) {
                    // 计算手续费
                    $public_service = $isRefundAll * 0.006;
                    $shop_service = $isRefundAll * $shop['ratio'] / 100;
                    $service = ceil(($public_service + $shop_service) * 100) / 100;

                    //重新计算收益
                    $profit = $isRefundAll - $service;
                    $shopOrderProfitModel->where('id', $orderProfit['id'])->update(['amount' => $profit]);
                }
            } else {
                $shopOrderProfitModel->where('order_id', $order['id'])->where('user_id', $shop['user_id'])->delete();

            }

            $userOrderProfitModel = new Userorderprofit();
            $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->delete();
        }

        //团购券
        if ($order['tuan_id'] != -1) {
            $userTuanModel = new Usertuan();
            $userTuanModel->where('order_id', $order['id'])->update(['status' => 'unuse']);
        }

        //恢复预定
        $roomBookOrderModel = new Shoproombook();
        $roomBookOrderModel->where('order_id', $order['id'])->delete();

        $cleanRoomModel = new Roomclean();
        $cleanRoomModel->where('order_id', $order['id'])->delete();


        $this->success('退款成功');


    }


    public function checkrefund()
    {

        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] != "payed") {
            $this->error("此订单状态不允许退款");
        }


        $time = strtotime("+1 hour", time());
        $fiveMintue = strtotime("-5 minute", time());


        $amount = $order['amount'];

        $shopModel = new \app\admin\model\Shop();


        $isKou = -1;
        if ($order['balance'] >= $amount) {
        } else {
            $refundAmount = $amount - $order['balance'];
            if ($order['create_time'] >= $fiveMintue) {
            } else {
                if ($time >= $order['book_start']) {
                    $isKou = 1;
                }
            }

        }


        $this->success('', $isKou);


    }

    public function leave()
    {
        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] == "paying" || $order['status'] == 'done' || $order['status'] == "refund") {
            $this->error("此订单状态不允许离店操作");
        }
        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();

        if ($org['leave_refund'] == -1) {
            $end = $order['book_end'];
            $hour = floor(($end - time()) % 86400 / 3600);

            $bookHour = floor(($end - $order['book_start']) % 86400 / 3600);
            $bookHour = ceil($bookHour);
            $payAmount = $order['pay_amount'];
            $price = $payAmount / $bookHour;
            if ($hour >= 1) {
                $hour = floor($hour);
                $payAmount = formatMoney($price * $hour);


                $refundOrder_no = getOrderSn();
                $orderParam = [
                    'out_trade_no' => $order['order_no'],
                    'out_refund_no' => $refundOrder_no,
                    'total_fee' => $order['pay_amount'] * 100,
                    'refund_fee' => $payAmount * 100,
                    'refund_desc' => '离店退款',
                ];


                $orgModel = new Org();
                $org = $orgModel->where('id', $order['org_id'])->find();
                $req = array();
                $req['mno'] = $org['mno'];
                $req['ordNo'] = $refundOrder_no;
                $req['origOrderNo'] = $order['order_no'];
                $req['amt'] = $payAmount;

                $vbillService = new VbillService();
                $ret = $vbillService->refund($req);
                $result = json_decode($ret, true);
                if ($result['respData']['bizCode'] != "0000") {
                    $this->error($result['respData']['bizMsg']);
                }

                $shopModel = new \app\admin\model\Shop();
                $shop = $shopModel->where('id', $order['shop_id'])->find();
                $amount = $order['pay_amount'] - $payAmount;
                $shopOrderModel->where('id', $order['id'])->update(['amount' => $amount, 'pay_amount' => $amount]);
                $shopOrderProfitModel = new Shoporderprofit();
                $profit = $amount - $amount * 0.006 - $amount * $shop['ratio'] / 100;
                $shopOrderProfitModel->where('order_id', $order['id'])->update(['amount' => $profit]);

            }
        }


        $shopOrderModel->where('id', $order['id'])->update(['status' => 'done']);
        $shopBookOrderModel = new Shoproombook();
        $shopBookOrderModel->where('order_id', $order['id'])->update(['status' => 'done']);
        $shopRoomModel = new Shoproom();
        $shopRoomModel->where('id', $order['room_id'])->update(['is_clean' => -1]);


        $shopDeviceModel = new Shopdevice();
        $device = $shopDeviceModel->where('room_id', $order['room_id'])->find();
        $sn = $device['sn'];
        $req = array();
        $req['sec'] = 0;
        $req['orderNo'] = $order_no;
        $req['sn'] = $sn;


        $ret = http_post_json($this->openCmdUrl, json_encode($req));
        $ret = json_decode($ret, true);


        $this->success('成功');

    }


    /**
     *带优惠券
     */
    public function orderInit3()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        $startCompareTime = strtotime($date . " " . $start);
        if ($startCompareTime <= time()) {
            $start = date("H:i");
        }


        $time = array();
        $hourArray = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->order('weigh', 'desc')->order('hour', 'asc')->select();

            $a = date("w", strtotime($date));
            if ($a == 0 || $a == 6) {
                $a = 2;
            } else {
                $a = 1;
            }
            $startTime = strtotime($date . " " . $start);
            $min = $hour * 60;
            $endTime = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


            $setList = array();
            foreach ($roomSet as $key => $val) {

                $dbStartTime = 0;
                $dbEndTime = 0;
                if ($val['time'] != "") {
                    $dbStartTime = strtotime($date . " " . $val['time']);
                    $dbEndTime = strtotime($date . " " . $val['end_time']);
                    if ($dbEndTime < $dbStartTime) {
                        $dbEndTime = date("Y-m-d", strtotime("+1 day", $dbStartTime)) . " " . $val['end_time'];
                    }
                }

                if ($val['is_week'] == 0 || $val['is_week'] == $a) {
                    if ($val['time'] == '') {
                        $setList[] = $val;
                    } else {
                        if ($startTime >= $dbStartTime && $endTime <= $dbEndTime) {
                            $setList[] = $val;
                        }
                    }
                }

            }


            foreach ($setList as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = $val['amount'];
                }
            }
            $roomSet = $setList;
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }
        $msg = "";

        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;

        $ret['total_price'] = round($totalPrice, 2);


        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {

            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }


        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;


        $ret['shop_name'] = $shop['name'];

        $this->success($msg, $ret);

    }


    /**
     *带优惠券
     */
    public function orderInit2()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        $startCompareTime = strtotime($date . " " . $start);
        if ($startCompareTime <= time()) {
            $start = date("H:i");
        }


        $time = array();
        $hourArray = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->order('weigh', 'desc')->order('hour', 'asc')->select();

            $a = date("w", strtotime($date));
            if ($a == 0 || $a == 6) {
                $a = 2;
            } else {
                $a = 1;
            }
            $startTime = strtotime($date . " " . $start);
            $min = $hour * 60;
            $endTime = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


            $setList = array();
            foreach ($roomSet as $key => $val) {

                $dbStartTime = 0;
                $dbEndTime = 0;
                if ($val['time'] != "") {
                    $dbStartTime = strtotime($date . " " . $val['time']);
                    $dbEndTime = strtotime($date . " " . $val['end_time']);
                    if ($dbEndTime < $dbStartTime) {
                        $dbEndTime = date("Y-m-d", strtotime("+1 day", $dbStartTime)) . " " . $val['end_time'];
                    }
                }

                if ($val['is_week'] == 0 || $val['is_week'] == $a) {
                    if ($val['time'] == '') {
                        $setList[] = $val;
                    } else {
                        if ($startTime >= $dbStartTime && $endTime <= $dbEndTime) {
                            $setList[] = $val;
                        }
                    }
                }

            }


            foreach ($setList as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = $val['amount'];
                }
            }
            $roomSet = $setList;
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }
        $msg = "";

        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();

            $mtCode = str_replace(" ", "", $mtCode);
            $meituanCode = $mtCode;
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) {

                $req = array();
                $req['code'] = $meituanCode;
                $req['shop_id'] = $room['shop_id'];

                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);

                if ($mtInfo['code'] == 200) {
                    $meituanUserCodeModel = new Usermeituancode();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    if ($mtCode['status'] == 'unuse') {
                        $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                        $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    }
                    $meituanModel = new Shopmeituan();
                    $meituan = $meituanModel->where('shop_id', $room['shop_id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                    if (!$mtCode) {
                        $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $meituanCode,
                            'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);

                    } else {
                    }
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                }
            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();

                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) {
                $dou_code = $douCode;
                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = "awoh1q4tfg29z1yv";
                $tokenReq["client_secret"] = "b8976219b329b01d543e76a83c923720";
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if (!$isWeek || !$isTime) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;

        $ret['total_price'] = round($totalPrice, 2);


        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {

            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }


        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;


        $ret['shop_name'] = $shop['name'];

        $this->success($msg, $ret);

    }


    public function orderInit4()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        $startCompareTime = strtotime($date . " " . $start);
        if ($startCompareTime <= time()) {
            $start = date("H:i");
        }


        $time = array();
        $hourArray = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->order('weigh', 'desc')->order('hour', 'asc')->select();

            $a = date("w", strtotime($date));
            if ($a == 0 || $a == 6) {
                $a = 2;
            } else {
                $a = 1;
            }
            $startTime = strtotime($date . " " . $start);
            $min = $hour * 60;
            $endTime = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


            $setList = array();
            foreach ($roomSet as $key => $val) {

                $dbStartTime = 0;
                $dbEndTime = 0;
                if ($val['time'] != "") {
                    $dbStartTime = strtotime($date . " " . $val['time']);
                    $dbEndTime = strtotime($date . " " . $val['end_time']);
                    if ($dbEndTime < $dbStartTime) {
                        $dbEndTime = date("Y-m-d", strtotime("+1 day", $dbStartTime)) . " " . $val['end_time'];
                    }
                }

                if ($val['is_week'] == 0 || $val['is_week'] == $a) {
                    if ($val['time'] == '') {
                        $setList[] = $val;
                    } else {
                        if ($startTime >= $dbStartTime && $endTime <= $dbEndTime) {
                            $setList[] = $val;
                        }
                    }
                }

            }


            foreach ($setList as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = $val['amount'];
                }
            }
            $roomSet = $setList;
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }
        $msg = "";

        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();

            $mtCode = str_replace(" ", "", $mtCode);
            $meituanCode = $mtCode;
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) {

                $req = array();
                $req['code'] = $meituanCode;
                $req['shop_id'] = $room['shop_id'];

                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);

                if ($mtInfo['code'] == 200) {
                    $meituanUserCodeModel = new Usermeituancode();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    if ($mtCode['status'] == 'unuse') {
                        $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                        $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    }
                    $meituanModel = new Shopmeituan();
                    $meituan = $meituanModel->where('shop_id', $room['shop_id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                    if (!$mtCode) {
                        $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $meituanCode,
                            'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);

                    } else {
                    }
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                }
            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();

                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) {
                $dou_code = $douCode;
                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = "awoh1q4tfg29z1yv";
                $tokenReq["client_secret"] = "b8976219b329b01d543e76a83c923720";
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;

        $ret['total_price'] = round($totalPrice, 2);


        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {

            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }


        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;


        $ret['shop_name'] = $shop['name'];


        $ret['discount'] = "";

        $userDiscountModel = new Userdiscount();
        $discountModel = new Shopdiscount();
        $discountList = $userDiscountModel->where('user_id', $user['id'])->where('status', 1)->where('valid_time', ">", time())->select();
        foreach ($discountList as $key => $val) {

            $discountId = $val['id'];
            $discount = $discountModel->where('id', $val['discount_id'])->find();

            $rule = json_decode($discount['rule'], true);


            $start = explode("~", $rule['time'])[0];
            $end = explode("~", $rule['time'])[1];

            $bookStart = $time1;
            $bookEnd = $time2;

            $startTime = strtotime($date . " " . $start);
            $endTime = strtotime($date . " " . $end);

            $isTime = false;
            if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                $isTime = true;
            }
            if ($start == '00:00' && $end == "23:59") {
                $isTime = true;
            }
            $week = $rule['week'];
            $isWeek = false;
            foreach ($week as $k2 => $v2) {
                if ($v2 == $day) {
                    $isWeek = true;
                    break;
                }
            }
            $isRoom = false;
            $roomList = $rule['room'];
            foreach ($roomList as $key => $val) {
                if ($val == $id) {
                    $isRoom = true;
                }
            }

            if ($isRoom && $isWeek && $isTime) {
                if ($discount['discount_type'] == '时长抵扣') {
                    if ($discount['discount_val'] >= $hour) {
                        $dObj = array();
                        $dObj['discount_name'] = $discount['name'];
                        $dObj['discount_type'] = $discount['discount_type'];
                        $dObj['discount_val'] = $discount['discount_val'];
                        $dObj['discount_id'] = $discountId;
                        $dObj['pay_price'] = 0;
                        $ret['discount'] = $dObj;
                    }
                } else {
                    $dObj = array();
                    $dObj['discount_name'] = $discount['name'];
                    $dObj['discount_type'] = $discount['discount_type'];
                    $dObj['discount_val'] = $discount['discount_val'];
                    $dObj['discount_id'] = $discountId;
                    if ($discount['discount_type'] == '金额抵扣') {
                        $discoutPrice = $ret['pay_price'] - $discount['discount_val'];
                        if ($discoutPrice < 0) $discoutPrice = 0;
                        $dObj['pay_price'] = $discoutPrice;

                    } else {
                        $dObj['pay_price'] = formatMoney($ret['pay_price'] * $discount['discount_val'] / 10);

                    }
                    $ret['discount'] = $dObj;
                }
            }

        }

        $this->success($msg, $ret);

    }

    public function orderInit5()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $ksCode = $this->request->param('ksCode');
        $couponId = $this->request->param('couponId');
        $setId = $this->request->param('setId');
        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }
        $newDate = $date;
        if ($startTime == '') {
            $start = date("H:i");
        }
        $set = null;
        $stWeek = date("w", strtotime($date . " " . $startTime));
        if ($stWeek == 0) {
            $stWeek = 7;
        }

        $newOrder_st = strtotime($date . " " . $startTime);
        $newOrder_et = $newOrder_st + $hour * 60 * 60;

        //判断是否营销套餐
        $isSaleSet = -1;
        if ($setId != "") {
            $roomSetModel = new Shoproomset();
            $set = $roomSetModel->where('id', $setId)->find();
            if ($set['time'] != "") $isSaleSet = 1;

        }
        $startCompareTime = strtotime($date . " " . $start);

        if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == 1) {

            $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
            $startCompareTime = strtotime($date . " " . $start);

        } else if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == -1) {

            $start = date("H:i");
        }

        $time = array();
        $hourArray = array();
        $newSetList = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            //$roomSet = $roomSetModel->where('room_id', $id)->where('time', '')->where('week', 'like', '%' . $stWeek . '%')->order('weigh', 'desc')->order('hour', 'asc')->select();
            $roomSet = $roomSetModel->where('room_id', $id)->where('time', '')->order('weigh', 'desc')->order('hour', 'asc')->select();


            $bookStart = strtotime($date . " " . $start);
            $bookEnd = strtotime("+" . ($hour * 60) . " minute", strtotime($date . " " . $start));

            //$newSetList = $roomSetModel->where('room_id', $id)->where('time', '<>', '')->where('week', 'like', '%' . $stWeek . '%')->order('weigh', 'desc')->order('hour', 'asc')->select();
            $newSetList = $roomSetModel->where('room_id', $id)->where('time', '<>', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

            foreach ($roomSet as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = formatMoney($val['amount']);
                }
            }

            if ($setId != "") {
                //$set  = $roomSetModel->where('id',$setId)->find();
                if ($set) {
                    $totalPrice = $set['amount'];
                }
            }
        }

        //新赋值
        $newTotalPrice = $totalPrice;

        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['yh_set'] = $newSetList;
        $ret['selectDate'] = $date;

        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }

        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();
        /**
         * 团购券使用价格计算
         */
        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();
            if ($userTuan) {
                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));
        }

        if (empty($tuanList)) {
            $totalPrice = $newTotalPrice;
        }

        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }

        $msg = "";
        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");
                list($start, $end) = explode('~', $meituan['use_time']);

                $isTime = false;
                if ($this->checkUseTime($newOrder_st, $newOrder_et, $meituan['use_time'])) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $isExist = false;
                $roomIds = json_decode($meituan['room_id'], true);
                if (in_array($id, $roomIds)) {
                    $isExist = true;
                } else {
                    $msg = "该美团券不适用此包厢";
                }

                $isWeek = false;
                $week = json_decode($meituan['week'], true);
                if (in_array($day, $week)) {
                    $isWeek = true;
                }

                if (!$isWeek || !$isTime) {
                    $msg = "预定时间不在美团券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                }
            } else {
                $msg = "美团券码状态非可用状态";
            }
        }

        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                list($start, $end) = explode('~', $dou['use_time']);

                $isTime = false;
                if ($this->checkUseTime($newOrder_st, $newOrder_et, $dou['use_time'])) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $isExist = false;
                $roomIds = json_decode($dou['room_id'], true);
                if (in_array($id, $roomIds)) {
                    $isExist = true;
                } else {
                    $msg = "该抖音券不适用此包厢";
                }

                $isWeek = false;
                $week = json_decode($dou['week'], true);
                if (in_array($day, $week)) {
                    $isWeek = true;
                }

                if (!$isWeek || !$isTime) {
                    $msg = "预定时间不在抖音券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                }
            } else {
                $msg = "抖音券非可使用状态";
            }
        }

        $ret['douCode'] = $douCode;
        $ret['total_price'] = round($totalPrice, 2);
        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {
            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }

        /**
         * 判断是和已预定的时间冲突
         */
        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
//        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
//        foreach ($tuanList as $key => $val) {
//            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));
//
//        }

        $ret['tuanList'] = $tuanList;
        $ret['shop_name'] = $shop['name'];

        $this->success($msg, $ret);

    }

    public function orderInit6()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');
        $setId = $this->request->param('setId');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        //判断是否营销套餐
        $isSaleSet = -1;
        if ($setId != "") {
            $roomSetModel = new Shoproomset();
            $set = $roomSetModel->where('id', $setId)->find();
            if ($set['time'] != "") $isSaleSet = 1;

        }
        $startCompareTime = strtotime($date . " " . $start);

        if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == 1) {

            $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
            $startCompareTime = strtotime($date . " " . $start);

        } else if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == -1) {

            $start = date("H:i");
        }

        $time = array();
        $hourArray = array();
        $newSetList = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->where('time', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

            $newSetList = $roomSetModel->where('room_id', $id)->where('time', '<>', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

            foreach ($roomSet as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = $val['amount'];
                }
            }

            if ($setId != "") {
                //$set  = $roomSetModel->where('id',$setId)->find();
                if ($set) {
                    $totalPrice = $set['amount'];
                }
            }
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['yh_set'] = $newSetList;
        $ret['selectDate'] = $date;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }

        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }
        $msg = "";

        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();

            $mtCode = str_replace(" ", "", $mtCode);
            $meituanCode = $mtCode;
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) {

                $req = array();
                $req['code'] = $meituanCode;
                $req['shop_id'] = $room['shop_id'];

                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);

                if ($mtInfo['code'] == 200) {
                    $meituanUserCodeModel = new Usermeituancode();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    if ($mtCode['status'] == 'unuse') {
                        $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                        $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    }
                    $meituanModel = new Shopmeituan();
                    $meituan = $meituanModel->where('shop_id', $room['shop_id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                    if (!$mtCode) {
                        $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $meituanCode,
                            'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);

                    } else {
                    }
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                }
            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();

                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) {
                $dou_code = $douCode;
                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = "awoh1q4tfg29z1yv";
                $tokenReq["client_secret"] = "b8976219b329b01d543e76a83c923720";
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;
        $ret['total_price'] = round($totalPrice, 2);

        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {

            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }

        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;
        $ret['shop_name'] = $shop['name'];
        $ret['discount'] = [];

        $userDiscountModel = new Userdiscount();
        $discountModel = new Shopdiscount();
        $discountList = $userDiscountModel->where('user_id', $user['id'])->where('status', 1)->where('valid_time', ">", time())->select();
        foreach ($discountList as $key => $val) {

            $discountId = $val['id'];
            $discount = $discountModel->where('id', $val['discount_id'])->find();

            $rule = json_decode($discount['rule'], true);


            $start = explode("~", $rule['time'])[0];
            $end = explode("~", $rule['time'])[1];

            $bookStart = $time1;
            $bookEnd = $time2;

            $startTime = strtotime($date . " " . $start);
            $endTime = strtotime($date . " " . $end);

            $isTime = false;
            if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                $isTime = true;
            }
            if ($start == '00:00' && $end == "23:59") {
                $isTime = true;
            }
            $week = $rule['week'];
            $isWeek = false;
            foreach ($week as $k2 => $v2) {
                if ($v2 == $day) {
                    $isWeek = true;
                    break;
                }
            }
            $isRoom = false;
            $roomList = $rule['room'];
            foreach ($roomList as $key => $val) {
                if ($val == $id) {
                    $isRoom = true;
                }
            }

            if ($isRoom && $isWeek && $isTime) {
                if ($discount['discount_type'] == '时长抵扣') {
                    if ($discount['discount_val'] >= $hour) {
                        $dObj = array();
                        $dObj['discount_name'] = $discount['name'];
                        $dObj['discount_type'] = $discount['discount_type'];
                        $dObj['discount_val'] = $discount['discount_val'];
                        $dObj['discount_id'] = $discountId;
                        $dObj['pay_price'] = 0;
                        $ret['discount'] = $dObj;
                    }
                } else {
                    $dObj = array();
                    $dObj['discount_name'] = $discount['name'];
                    $dObj['discount_type'] = $discount['discount_type'];
                    $dObj['discount_val'] = $discount['discount_val'];
                    $dObj['discount_id'] = $discountId;
                    if ($discount['discount_type'] == '金额抵扣') {
                        $discoutPrice = $ret['pay_price'] - $discount['discount_val'];
                        if ($discoutPrice < 0) $discoutPrice = 0;
                        $dObj['pay_price'] = $discoutPrice;

                    } else {
                        $dObj['pay_price'] = formatMoney($ret['pay_price'] * $discount['discount_val'] / 10);

                    }
                    $ret['discount'] = $dObj;
                }
            }

        }

        $this->success($msg, $ret);

    }


    public function orderInit7()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');
        $discountId = $this->request->param('discountId');
        if ($discountId == "") $discountId = -1;

        $setId = $this->request->param('setId');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        //判断是否营销套餐
        $isSaleSet = -1;
        if ($setId != "") {
            $roomSetModel = new Shoproomset();
            $set = $roomSetModel->where('id', $setId)->find();
            if ($set['time'] != "") $isSaleSet = 1;
        }
        $startCompareTime = strtotime($date . " " . $start);

        if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == 1) {

            $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
            $startCompareTime = strtotime($date . " " . $start);

        } else if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == -1) {

            $start = date("H:i");
        }

        $time = array();
        $hourArray = array();
        $newSetList = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->where('time', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

            $newSetList = $roomSetModel->where('room_id', $id)->where('time', '<>', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

            foreach ($roomSet as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = $val['amount'];
                }
            }

            if ($setId != "") {
                //$set  = $roomSetModel->where('id',$setId)->find();
                if ($set) {
                    $totalPrice = $set['amount'];
                }
            }
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['yh_set'] = $newSetList;
        $ret['selectDate'] = $date;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }



        $yxList = array();
        foreach ($newSetList as $key=>$val){

            $set_time = $val['time'] . '~' . $val['end_time'];
            $isCheckSetTimeWeek = false;
            $isCheckSetTimeTime = false;
            if (in_array($day, json_decode($val['week'],true))) {
                $isCheckSetTimeWeek = true;
            }
            if($val['time'] == '00:00' && $val['end_time'] == '23:59'){
                $isCheckSetTimeTime = true;
            }else{
                if ($this->checkUseTime(strtotime($ret['start']), strtotime($ret['end']), $set_time)) {
                    $isCheckSetTimeTime = true;
                }
            }

            if($isCheckSetTimeTime == true && $isCheckSetTimeWeek == true){
                $yxList[] = $val;
            }

        }
        $ret['yh_set'] = $yxList;


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }
        $msg = "";

        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();

            $mtCode = str_replace(" ", "", $mtCode);
            $meituanCode = $mtCode;
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) {

                $req = array();
                $req['code'] = $meituanCode;
                $req['shop_id'] = $room['shop_id'];

                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);

                if ($mtInfo['code'] == 200) {
                    $meituanUserCodeModel = new Usermeituancode();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    if ($mtCode['status'] == 'unuse') {
                        $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                        $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    }
                    $meituanModel = new Shopmeituan();
                    $meituan = $meituanModel->where('shop_id', $room['shop_id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                    if (!$mtCode) {
                        $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $meituanCode,
                            'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);

                    } else {
                    }
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                }
            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();

                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) {
                $dou_code = $douCode;
                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = "awoh1q4tfg29z1yv";
                $tokenReq["client_secret"] = "b8976219b329b01d543e76a83c923720";
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;
        $ret['total_price'] = round($totalPrice, 2);

        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {

            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }

        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;
        $ret['shop_name'] = $shop['name'];
        $ret['discount'] = [];

        $userDiscountModel = new Userdiscount();
        $discountModel = new Shopdiscount();
        if ($discountId == -1) {

            $checkDiscountList = array();
            $discountList = $userDiscountModel->where('user_id', $user['id'])->where('status', 1)->where('valid_time', ">", time())->select();
            foreach ($discountList as $key => $val) {

                $discountId = $val['id'];
                $discount = $discountModel->where('id', $val['discount_id'])->find();
                $discount['id'] = $val['id'];
                $discount['discount_id'] = $val['discount_id'];

                $rule = json_decode($discount['rule'], true);


                $start = explode("~", $rule['time'])[0];
                $end = explode("~", $rule['time'])[1];

                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = $rule['week'];
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                $isRoom = false;
                $roomList = $rule['room'];
                foreach ($roomList as $key => $val) {
                    if ($val == $id) {
                        $isRoom = true;
                    }
                }


                if ($isRoom && $isWeek && $isTime) {

                    $checkDiscountList[] = $discount;

                }

            }
            $ret['discount'] = $checkDiscountList;

        } else {
            $userDiscount = $userDiscountModel->where('id', $discountId)->find();
            $discount = $discountModel->where('id', $userDiscount['discount_id'])->find();

            $rule = json_decode($discount['rule'], true);


            $start = explode("~", $rule['time'])[0];
            $end = explode("~", $rule['time'])[1];

            $bookStart = $time1;
            $bookEnd = $time2;

            $startTime = strtotime($date . " " . $start);
            $endTime = strtotime($date . " " . $end);

            $isTime = false;
            if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                $isTime = true;
            }
            if ($start == '00:00' && $end == "23:59") {
                $isTime = true;
            }
            $week = $rule['week'];
            $isWeek = false;
            foreach ($week as $k2 => $v2) {
                if ($v2 == $day) {
                    $isWeek = true;
                    break;
                }
            }
            $isRoom = false;
            $roomList = $rule['room'];
            foreach ($roomList as $key => $val) {
                if ($val == $id) {
                    $isRoom = true;
                }
            }

            if ($isRoom && $isWeek && $isTime) {


                if ($discount['discount_type'] == '时长抵扣') {
                    if ($discount['discount_val'] >= $hour) {
                        $ret['pay_price'] = 0;
                    }
                } else {
                    if ($discount['discount_type'] == '金额抵扣') {
                        $discoutPrice = $ret['pay_price'] - $discount['discount_val'];
                        if ($discoutPrice < 0) $discoutPrice = 0;
                        $ret['pay_price'] = $discoutPrice;
                    } else {
                        $ret['pay_price'] = formatMoney($ret['pay_price'] * $discount['discount_val'] / 10);
                    }

                }


            }


        }


        $this->success($msg, $ret);

    }

    public function orderInit8()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');
        $discountId = $this->request->param('discountId');
        if ($discountId == "") $discountId = -1;

        $setId = $this->request->param('setId');

        $start = explode("-", $startTime)[0];

        if ($date == '') {
            $date = date("Y-m-d");
        }

        //判断是否营销套餐
        $isSaleSet = -1;
        if ($setId != "") {
            $roomSetModel = new Shoproomset();
            $set = $roomSetModel->where('id', $setId)->find();
            if ($set['time'] != "") $isSaleSet = 1;

        }
        $startCompareTime = strtotime($date . " " . $start);

        if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == 1) {

            $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
            $startCompareTime = strtotime($date . " " . $start);

        } else if ($startCompareTime <= strtotime("-10 minute") && $isSaleSet == -1) {

            $start = date("H:i");
        }

        $time = array();
        $hourArray = array();
        $newSetList = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        $per_amount = 0;//增加一个单价，方便后面时长抵扣券计算
        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 3; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $per_amount = $room['hour_price'];
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $per_amount = $room['hour_price'];
            $totalPrice = $hour * $room['hour_price'];
            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->where('time', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

            $newSetList = $roomSetModel->where('room_id', $id)->where('time', '<>', '')->order('weigh', 'desc')->order('hour', 'asc')->select();

//            foreach ($roomSet as $key => $val) {
//                if ($hour == $val['hour']) {
//                    $per_amount = ceil($val['amount'] / $val['hour'] * 100) / 100;
//                    $totalPrice = $val['amount'];
//                    break;
//                }
//            }

            if ($setId != "") {
                $set = $roomSetModel->where('id', $setId)->find();
                if ($set) {
                    $per_amount = ceil($set['amount'] / $set['hour'] * 100) / 100;
                    $totalPrice = $set['amount'];
                }
            }
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);
        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['yh_set'] = $newSetList;
        $ret['selectDate'] = $date;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = formatMoney($balance + $allBalance);
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        if ($shop['is_join_balance'] == 1) {
            $balance = formatMoney($balance + $allBalance);
        }

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;

        $ret['start'] = date("Y-m-d H:i", $startCompareTime);
        $ret['end'] = date("Y-m-d H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));


        $dayTime = strtotime($date . " " . $ret['startTime']);
        $day = date("w", $dayTime);
        if ($day == 0) {
            $day = 7;
        }

        $yxList = array();
        foreach ($newSetList as $key=>$val){

            $set_time = $val['time'] . '~' . $val['end_time'];
            $isCheckSetTimeWeek = false;
            $isCheckSetTimeTime = false;
            if (in_array($day, json_decode($val['week'],true))) {
                $isCheckSetTimeWeek = true;
            }
            if($val['time'] == '00:00' && $val['end_time'] == '23:59'){
                $isCheckSetTimeTime = true;
            }else{
                if ($this->checkUseTime(strtotime($ret['start']), strtotime($ret['end']), $set_time)) {
                    $isCheckSetTimeTime = true;
                }
            }

            if($isCheckSetTimeTime == true && $isCheckSetTimeWeek == true){
                $yxList[] = $val;
            }

        }
        $ret['yh_set'] = $yxList;


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $pay_price = $totalPrice;
        $userCouponModel = new Usercoupon();
        if ($couponId != -1 && $mtCode == '' && $douCode == '') {
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCouponModel = new Shopcoupon();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {

                $pay_price = $totalPrice - $shopCoupon['amount'];
            }
        }
        $msg = "";

        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();

            $mtCode = str_replace(" ", "", $mtCode);
            $meituanCode = $mtCode;
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) {

                $req = array();
                $req['code'] = $meituanCode;
                $req['shop_id'] = $room['shop_id'];

                $meituanService = new MeituanService();
                $mtInfo = $meituanService->prepare($req);

                if ($mtInfo['code'] == 200) {
                    $meituanUserCodeModel = new Usermeituancode();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    if ($mtCode['status'] == 'unuse') {
                        $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                        $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                    }
                    $meituanModel = new Shopmeituan();
                    $meituan = $meituanModel->where('shop_id', $room['shop_id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                    if (!$mtCode) {
                        $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $meituanCode,
                            'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);

                    } else {
                    }
                    $mtCode = $meituanUserCodeModel->where('mt_code', $meituanCode)->find();
                }
            }

            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();

                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }


            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) {
                $dou_code = $douCode;
                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = "awoh1q4tfg29z1yv";
                $tokenReq["client_secret"] = "b8976219b329b01d543e76a83c923720";
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($dou_code, 0, 5) == "https") {

                    $headers = get_headers($dou_code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $dou_code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('sku_id', $skuId)->find();
                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $dou_code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $dou_code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop['id']]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();


            }
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);


                $bookStart = strtotime($date . " " . $ret['startTime']);
                $bookEnd = strtotime($date . " " . $ret['endTime']);

                if ($bookStart > $bookEnd) {
                    $date2 = date("Y-m-d", strtotime("+1 day", $bookStart));

                    $bookEnd = strtotime($date2 . " " . $ret['endTime']);
                }

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek == false || $isTime == false) {
                    $msg = "预定时间不在券使用范围内";
                }

                //error_log($isWeek."======orderIninit2====".$isTime."====ss===".$isExist);
                if ($isWeek && $isTime && $isExist) {
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                } else {
                    $ret['douCode'] = "";
                }
            }

        }

        $ret['douCode'] = $douCode;
        $ret['total_price'] = round($totalPrice, 2);

        $ret['status'] = $room['status'];
        $ret['orderEndTime'] = "";

        if ($room['status'] == 'busy') {

            $bookRoomModel = new Shoproombook();
            $roomBook = $bookRoomModel->where('room_id', $room['id'])->where('status', 'doing')->order('id', 'desc')->find();
            if ($roomBook) {
                $ret['orderEndTime'] = date("H:i", $roomBook['end_time']);
            }
        }

        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if ($time2 < $time1) {
            $date2 = date("Y-m-d", strtotime("+1 day", $time1));
            $time2 = strtotime($date2 . " " . $ret['endTime']);
        }

        $userCouponModel = new Usercoupon();
        if ($couponId != -1) {
            $couponList = array();
            $coupon = $userCouponModel->with(['coupon'])->where('coupon_id', $couponId)->find();
            $couponList[] = $coupon;
        } else {
            $couponList = $userCouponModel->checkCoupon($id, $user['id'], $time1, $time2, $pay_price);
        }
        $ret['couponList'] = $couponList;

        $dis_price = 0;
        if ($tuanId == -1 && $couponId == -1) {

            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'], $time1, $time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));

        }
        $ret['tuanList'] = $tuanList;
        $ret['shop_name'] = $shop['name'];
        $ret['discount'] = [];

        $userDiscountModel = new Userdiscount();
        $discountModel = new Shopdiscount();
        if ($discountId == -1) {

            $checkDiscountList = array();
            $discountList = $userDiscountModel->where('user_id', $user['id'])->where('status', 1)->where('valid_time', ">", time())->select();
            foreach ($discountList as $key => $val) {

                $discountId = $val['id'];
                $discount = $discountModel->where('id', $val['discount_id'])->find();
                $discount['id'] = $val['id'];
                $discount['discount_id'] = $val['discount_id'];

                $rule = json_decode($discount['rule'], true);


                $start = explode("~", $rule['time'])[0];
                $end = explode("~", $rule['time'])[1];

                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = $rule['week'];
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }
                $isRoom = false;
                $roomList = $rule['room'];
                foreach ($roomList as $key => $val) {
                    if ($val == $id) {
                        $isRoom = true;
                    }
                }


                if ($isRoom && $isWeek && $isTime) {

                    $checkDiscountList[] = $discount;

                }

            }
            $ret['discount'] = $checkDiscountList;

        } else {
            $userDiscount = $userDiscountModel->where('id', $discountId)->find();
            $discount = $discountModel->where('id', $userDiscount['discount_id'])->find();

            $rule = json_decode($discount['rule'], true);


            $start = explode("~", $rule['time'])[0];
            $end = explode("~", $rule['time'])[1];

            $bookStart = $time1;
            $bookEnd = $time2;

            $startTime = strtotime($date . " " . $start);
            $endTime = strtotime($date . " " . $end);

            $isTime = false;
            if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                $isTime = true;
            }
            if ($start == '00:00' && $end == "23:59") {
                $isTime = true;
            }
            $week = $rule['week'];
            $isWeek = false;
            foreach ($week as $k2 => $v2) {
                if ($v2 == $day) {
                    $isWeek = true;
                    break;
                }
            }
            $isRoom = false;
            $roomList = $rule['room'];
            foreach ($roomList as $key => $val) {
                if ($val == $id) {
                    $isRoom = true;
                }
            }

            if ($isRoom && $isWeek && $isTime) {
                if ($discount['discount_type'] == '时长抵扣') {
                    if ($discount['discount_val'] >= $hour) {
                        $ret['pay_price'] = 0;
                    } else {
                        $diff_hour = $hour - $discount['discount_val'];
                        $ret['pay_price'] = $per_amount * $diff_hour;
                    }
                } else {
                    if ($discount['discount_type'] == '金额抵扣') {
                        $discoutPrice = $ret['pay_price'] - $discount['discount_val'];
                        if ($discoutPrice < 0) $discoutPrice = 0;
                        $ret['pay_price'] = $discoutPrice;
                    } else {
                        $ret['pay_price'] = formatMoney($ret['pay_price'] * $discount['discount_val'] / 10);
                    }

                }


            }


        }

        $this->success($msg, $ret);

    }


    /**
     * 带优惠券
     */
    public function addBookOrderFz2()
    {
        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $setId = $this->request->param('setId');//套餐ID 如果ID 为-1 就是时间预定
        $tuanId = $this->request->param('tuanId');
        $mt_code = $this->request->param('mtCode');
        $orgId = $this->request->param('orgId');
        $dou_code = $this->request->param('douCode');
        $couponId = $this->request->param('couponId');


        /**
         * 判断是和已预定的时间冲突
         */

        $time1 = strtotime($date . " " . $startTime);
        $day = date("w", $time1);
        if ($day == 0) {
            $day = 7;
        }


        $min = $hour * 60;

        $endStrotime = strtotime("+" . $min . " minute", strtotime($date . " " . $startTime));

        $time2 = $endStrotime;


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time2)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->where("end_time", "<=", $time2)->find();
        $checkEnd4 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null || $checkEnd4 != null) {
            $this->error("此时间段已被预定");
        }

        $shopOrderModel = new Shoporder();
        $user = $this->auth->getUser();

        $checkStart2 = $shopOrderModel->where('user_id', "<>", $user['id'])->where('status', 'paying')->where('room_id', $id)->where('book_start', "<=", $time1)->where("book_end", ">=", $time2)->order('create_time', 'desc')->find();

        $checkMowTime = strtotime("-20 seconds", time());
        $isBookIng = -1;
        if ($checkStart2 && $checkStart2['create_time'] > $checkMowTime) {

            $isBookIng = 1;

        }
        if ($isBookIng == -1) {
            $checkEnd2 = $shopOrderModel->where('user_id', "<>", $user['id'])->where('status', 'paying')->where('room_id', $id)->where('book_start', ">=", $time1)->where('book_start', "<=", $time2)->where("book_end", ">=", $time2)->order('create_time', 'desc')->find();
            if ($checkEnd2 && $checkEnd2['create_time'] > $checkMowTime) {
                $isBookIng = 1;
            }
        }

        if ($isBookIng == -1) {
            $checkEnd32 = $shopOrderModel->where('user_id', "<>", $user['id'])->where('status', 'paying')->where('room_id', $id)->where('book_start', "<=", $time1)->where('book_end', ">=", $time1)->where("book_end", "<=", $time2)->order('create_time', 'desc')->find();
            if ($checkEnd32 && $checkEnd32['create_time'] > $checkMowTime) {
                $isBookIng = 1;
            }
        }

        if ($isBookIng == 1) {
            $this->error("此时间段正在有人预定，请稍后再试");
        }


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();

        if ($orgId == "") {
            $orgId = $shop['org_id'];
        }

        $orderPrice = 0;
        if ($setId == -1) {
            $totalPrice = $hour * $room['hour_price'];
            $orderPrice = $totalPrice;
        } else {
            $shopRoomBookSetModel = new Shoproomset();
            $set = $shopRoomBookSetModel->where('id', $setId)->find();
            $totalPrice = $set['amount'];
            $orderPrice = $totalPrice;
        }


        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();
        if ($tuanId != -1 && $mt_code == "" && $dou_code == "") {
            $userTuan = $tuanUserModel->where('user_id', $user['id'])->where('id', $tuanId)->where('status', 'unuse')->order('valid_time', 'asc')->find();

            if ($userTuan) {


                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    if ($tuan) {
                        $tuanHour = $tuan['hour'];
                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }

        if ($couponId != -1 && $mt_code == "" && $dou_code == "") {
            $userCouponModel = new Usercoupon();
            $shopCouponModel = new Shopcoupon();
            $userCoupon = $userCouponModel->where('id', $couponId)->find();
            $shopCoupon = $shopCouponModel->where('id', $userCoupon['coupon_id'])->find();
            if ($userCoupon['valid_time'] > time() && $userCoupon['status'] == 'unuse') {
                $totalPrice = $orderPrice - $shopCoupon['amount'];
            }
        }

        $mtService = new MtService();
        $userMtCodeModel = new Usermeituancode();

        if ($mt_code != '') {
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");


                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }

                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                } else {

                }

            }

            //官方校验美团券
            $mtReq = array();
            $mtReq['shop_id'] = $shop['id'];
            $mtReq['code'] = $mt_code;

            $mtInfo = $mtService->couponInfo($mtReq);
            if ($mtInfo['code'] != 200) {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'bad']);
                $this->error("此券不用");
            }
        }

        $douVerifyToken = "";
        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('shop_id', $room['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;


                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {


                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if ($douVerifyToken == '') {
                        $this->error("此券为无效券");
                    }
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }

                } else {
                    $this->error("此券不能可用");
                }
            }

        }


        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;

        if ($totalPrice > 0) {
            if ($balance > 0 && $mt_code == "" && $dou_code == "" && $couponId == -1 && $tuanId == -1) {
                $type = "balance";
                if ($balance >= $totalPrice) {
                    $dis_price = $totalPrice;
                    $pay_price = 0;
                } else {
                    $dis_price = $balance;
                    $pay_price = $totalPrice - $balance;
                }

            }
        }

        if ($pay_price < 0) {
            $this->error("金额不对，请重新提交");
        }

        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $orderPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $time1;
        $db['book_end'] = $time2;
        $db['set_id'] = $setId;
        $db['tuan_id'] = $tuanId;
        $db['balance'] = $dis_price;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;
        $db['org_id'] = $orgId;
        $db['coupon_id'] = $couponId;

        $db['pay_rate'] = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
        $price = $pay_price - $db['pay_rate'];
        $db['rate'] = formatMoney($shop['ratio'] * $price / 100);


        $code = mt_rand(100000, 999999);
        $db['open_code'] = "";

        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        if ($id > 0) {

            if ($mt_code != "") {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'lock']);
            }
            if ($dou_code != "") {

                $userDouCodeModel->where('dou_code', $dou_code)->update(['status' => 'lock', 'order_id' => $id]);
            }

            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定" . $hour . "小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/order/sxfOrderCallback";

                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();

                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
                $mno = $org['mno'];
                if ($shopMno) {
                    if ($shopMno['ratio'] == 100) {
                        //走挂靠
                        $mno = $shopMno['mno'];
                    } else {
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

                        $realPay = formatMoney($pay_price - $pay_price * 0.006);
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }

                $req['mno'] = $mno;
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = "包厢预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }
            } else {

                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                if ($tuanId != -1) {
                    $tuanUserModel->where('id', $tuanId)->update(['status' => 'used']);
                }

                $order = $shopOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    $isChecked = $mtService->syncMt($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");
                }
                if ($couponId != -1) {
                    $userCouponModel = new Usercoupon();
                    $userCouponModel->where('id', $couponId)->update(['status' => 'used']);
                }

                if ($dou_code != "") {
                    $douService = new DouService();
                    $isChecked = $douService->verifyCode($order);
                    if ($isChecked == 0) $this->error("验券失败，请联系商家");

                }

                $this->redis->set($order['shop_id'], time());
                $roomService = new RoomService();
                $roomService->addBookData($order);
                $shopOrderModel->where('id', $id)->update(['status' => 'payed', 'update_time' => time()]);


                $mpService = new MpService();
                $mpWxModel = new Userweixinmp();
                $shopModel = new \app\admin\model\Shop();
                $shop = $shopModel->where('id', $order['shop_id'])->find();
                $wx = $mpWxModel->where('mobile', $shop['mobile'])->find();
                if ($wx) {


                    $userModel = new \app\admin\model\User();
                    $user = $userModel->where('id', $order['user_id'])->find();
                    $msg = array();
                    $msg['openid'] = $wx['openid'];
                    $msg['room'] = $order['room_name'];
                    $msg['amount'] = $order['amount'];
                    $msg['phone'] = $user['mobile'];
                    $msg['time'] = date("Y-m-d H:i", $order['book_start']);
                    $msg['endTime'] = date("Y-m-d H:i", $order['book_end']);


                    $mpService->addOrderNotify($this->wxApp, $msg);


                }

            }


            if ($type == "balance") {

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                    'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
            }


            $this->success('下单成功', $info);
        } else {
            $this->error("订单生成失败,请联系客服");
        }

    }


    public function codeXu()
    {
        $code = $this->request->param('code');
        $code = str_replace(" ", "", $code);
        $user = $this->auth->getUser();
        $brand = $this->request->param('brand');

        $orderNo = $this->request->param('order_no');
        $starTime = strtotime("-10 minute", time());

        $roomBookModel = new Shoproombook();
        if ($orderNo != "") {
            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $orderNo)->find();
            $book = $roomBookModel->where('order_id', $order['id'])->find();
        } else {
            $book = $roomBookModel->where('status', 'in', ['doing', 'done'])->
            where('user_id', $user['id'])->order('end_time', 'desc')->find();

        }

        if ($book['end_time'] < $starTime) {
            $this->error("您没有可续费的订单");
        }
        if ($book['end_time'] - time() < 0) {
            $minute = 0;
        } else {
            $minute = floor(($book['end_time'] - time()) % 86400 / 60);
        }
        $day = date("w", time());
        if ($day == 0) {
            $day = 7;
        }
        $date = date("Y-m-d");
        $shopModel = new Shop();
        $shopRoomModel = new Shoproom();
        $shop = $shopModel->where('id', $book['shop_id'])->find();

        $douVerifyToken = "";
        $amount = 0;
        $room = $shopRoomModel->where('id', $book['room_id'])->find();
        if (strlen($code) <= 13) {
            //美团
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $code)->find();
            if (!$mtCode) {

                $req = array();
                $req['code'] = $code;
                $req['shop_id'] = $book['shop_id'];

                if ($shop['mt2_token'] != "") {
                    $meituanService = new MeituanService();
                    $mtInfo = $meituanService->prepare($req);
                } else {
                    $mtService = new MtService();
                    $mtInfo = $mtService->couponInfo($req);
                }

                if ($mtInfo['code'] != 200) {
                    $this->error($mtInfo['msg']);
                }

                $meituanUserCodeModel = new Usermeituancode();

                $mtCode = $meituanUserCodeModel->where('mt_code', $code)->find();
                if ($mtCode['status'] == 'unuse') {
                    $meituanUserCodeModel->where('id', $mtCode['id'])->delete();
                    $mtCode = $meituanUserCodeModel->where('mt_code', $code)->find();
                }
                $meituanModel = new Shopmeituan();
                $meituan = $meituanModel->where('shop_id', $book['shop_id'])->where('dealgroup_id', $mtInfo['data']['dealgroup_id'])->find();
                if (!$mtCode) {
                    $meituanUserCodeModel->insertGetId(['user_id' => $user['id'], 'mt_code' => $code,
                        'create_time' => time(), 'status' => 'unuse', 'order_id' => -1, 'group_id' => $meituan['id'], 'shop_id' => $meituan['shop_id']]);
                } else {
                    $mtCode['id'];
                }
                $amount = $meituan['price'];
                $mtCode = $userMtCodeModel->where('mt_code', $code)->find();

            }
            $id = $book['room_id'];
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = time();
                $bookEnd = strtotime("+" . $meituan['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }


                if ($isWeek && $isTime && $isExist) {

                    $amount = $meituan['price'];

                    //官方校验美团券
                    $mtReq = array();
                    $mtReq['shop_id'] = $book['shop_id'];
                    $mtReq['code'] = $code;

                    if ($shop['mt2_token'] != "") {
                        $meituanService = new MeituanService();
                        $mtInfo = $meituanService->prepare($mtReq);
                    } else {
                        $mtService = new MtService();
                        $mtInfo = $mtService->couponInfo($mtReq);
                    }
                    if ($mtInfo['code'] != 200) {
                        $this->error("此券不用");
                    }
                    $hour = $meituan['hour'];
                } else {
                    $this->error("不在时间使用范围内");

                }
            }

        } else {
            //抖音
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $code)->find();
            if (!$douCodeDb) {

                $curlService = new CurlService();
                $tokenUrl = "https://open.douyin.com/oauth/client_token/";
                $tokenReq = array();
                $tokenReq["client_key"] = CurlService::$appKey;
                $tokenReq["client_secret"] = CurlService::$secret;
                $tokenReq["grant_type"] = "client_credential";

                $result = $curlService->curl_post($tokenUrl, $tokenReq);
                $token = $result['data']['access_token'];

                if (substr($code, 0, 5) == "https") {

                    $headers = get_headers($code, TRUE);
                    $reqUrl = $headers['Location'];
                    $data = parse_url($reqUrl);
                    parse_str($data['query'], $results);
                    $objData = $results['object_id'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
                } else {
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $code;
                }


                $result = $curlService->http_curl_get($url, $token);

                if ($result['data']['error_code'] != 0) {
                    $this->error($result['data']['description']);
                }
                $certificates = $result['data']['certificates'];
                if (count($certificates) == 0) {
                    $this->error("此券码错误");
                }

                $skuId = $certificates[0]['sku']['sku_id'];

                $shopDouModel = new Shopdou();
                $shopDou = $shopDouModel->where('shop_id', $book['shop_id'])->where('sku_id', $skuId)->find();
                $amount = $shopDou['price'];

                if (!$shopDou) $this->error("店铺未同步该券产品，请联系商家");
                $shop_id = $shopDou['shop_id'];


                $douUserCodeModel = new Userdoucode();
                $userCode = $douUserCodeModel->where('dou_code', $code)->find();
                if (!$userCode) {
                    $douUserCodeModel->insertGetId(['user_id' => $user['id'], 'dou_code' => $code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop_id]);
                } else {
                    $douUserCodeModel->where('id', $userCode['id'])->update(['user_id' => $user['id'], 'dou_code' => $code, 'create_time' => time(), 'sku_id' => $skuId, 'shop_id' => $shop_id]);
                    $userCode['id'];
                }
                $douCodeDb = $userDouCodeModel->where('dou_code', $code)->find();
            }

            $id = $book['room_id'];
            if ($douCodeDb['status'] == 'unuse') {

                $dou = $shopDouModel->where('shop_id', $douCodeDb['shop_id'])->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);

                $isExist = false;

                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                $bookStart = time();
                $bookEnd = strtotime("+" . $dou['hour'] . " hour", $bookStart);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if ($start == '00:00' && $end == "23:59") {
                    $isTime = true;
                }
                $week = json_decode($dou['week'], true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if ($isWeek && $isTime && $isExist) {

                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($code);
                    if ($douVerifyToken == '') {
                        $dou_code = "";
                        $this->error("此券为无效券");
                    }
                    $amount = $dou['price'];
                    $hour = $dou['hour'];
                    $pay_amount = 0;
                    $pay_price = 0;
                } else {
                    $dou_code = "";
                    $this->error("券不在使用时间范围内");
                }
            }

        }


        $xuMin = $hour * 60;


        $startTime = time();
        if ($book['end_time'] - $startTime > 0) {
            $haveMin = floor(($book['end_time'] - $startTime) % 86400 / 60);
        } else {
            $haveMin = 0;
        }


        $totalMin = $haveMin + $xuMin;

        $endTime = strtotime("+" . $totalMin . " minute", time());


//        $checkStart = $roomBookModel->where('room_id', $id)->where('start_time', "<=", $startTime)->where("end_time", ">=", $endTime)->find();
//        $checkEnd = $roomBookModel->where('room_id', $id)->where('start_time', "<=", $endTime)->where("end_time", ">=", $endTime)->find();
//
//        if ($checkStart != null || $checkEnd != null) {
//
//            if ($checkStart['id'] != $id || $checkEnd['id'] == $id) {
//                $this->error("此时间段预被预定,无法续费");
//            }
//        }


        $isBooked = -1;
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('order_id', '<>', $book['order_id'])->where('room_id', $id)->where('status', 'in', ['undo', 'doing'])->order('start_time', 'desc')->select();
        foreach ($bookList as $key => $val) {

            $start = $val['start_time'];
            $end = $val['end_time'];
            if ($startTime <= $start && $endTime >= $end) $isBooked = 1;//全包围
            if ($startTime >= $start && $endTime <= $end) $isBooked = 1;//在区间范围内
            if ($startTime <= $end && $endTime > $end) $isBooked = 1; //
            if ($startTime < $start && $endTime <= $end && $endTime >= $start) $isBooked = 1;

        }
        if ($isBooked == 1) $this->error("此时间段已被预定");


        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $book['shop_id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $amount;
        $db['pay_amount'] = 0;
        $db['book_start'] = $startTime;
        $db['book_end'] = $endTime;
        $db['set_id'] = -1;
        $db['balance'] = 0;
        $db['org_id'] = 27;
        $db['dou_token'] = $douVerifyToken;

        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        $orderModel = new Shoporder();

        if ($id > 0) {
            if (strlen($code) <= 12) {
                $shopOrderModel->where('id', $id)->update(['mt_code' => $code]);
                $order = $orderModel->where('order_no', $orderNo)->find();

                if ($shop['mt2_token'] != "") {
                    $meituanService = new MeituanService();
                    $isChecked = $meituanService->consume($order);
                } else {
                    $mtService = new MtService();
                    $isChecked = $mtService->syncMt($order);
                }
                if ($isChecked == 0) $this->error("验券失败，请联系商家");
            } else {
                $shopOrderModel->where('id', $id)->update(['dou_code' => $code]);
                $order = $orderModel->where('order_no', $orderNo)->find();

                $douService = new DouService();
                $isChecked = $douService->verifyCode($order);
                if ($isChecked == 0) $this->error("验券失败，请联系商家");
            }

            $orderModel = new Shoporder();
            $orderModel->where('order_no', $orderNo)->update(['status' => 'doing']);

            $order = $shopOrderModel->where('id', $id)->find();
            $bookModel = new Shoproombook();

            $lastOrder = $shopOrderModel->where('user_id', $order['user_id'])->where('status', 'doing')->find();
            if ($lastOrder) {
                $shopOrderModel->where('id', $lastOrder['id'])->update(['status' => 'done']);
                $bookModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);
            }


            $roomService = new RoomService();
            $roomService->addBookData($order);


            $bookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
            $this->redis->set($order['shop_id'], time());

            $deviceService = new DeviceService();
            $book = $bookModel->where('order_id', $order['id'])->find();

            $shopRoomModel = new Shoproom();
            $shopRoomModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


            $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);
            $this->success('', $orderNo);
        } else {
            $this->error("续时失败");
        }


    }


    public function comment()
    {
        $orderId = $this->request->param('order_id');
        $dou_code = $this->request->param('dou_code');
        $mt_code = $this->request->param('mt_code');
        $type = $this->request->param('type');
        $image = $this->request->param('image');

        $user = $this->auth->getUser();
        $commentModel = new Comment();
        $comment = $commentModel->where('order_id', $orderId)->find();
        if ($comment) $this->error("此券已评论，无须评论");


        $db = array();
        $db['user_id'] = $user['id'];
        $db['dou_code'] = $dou_code;
        $db['mt_code'] = $mt_code;
        $db['order_id'] = $orderId;
        $db['create_time'] = time();
        if ($type == 'qp') {
            $db['hour'] = 1;
        } else {
            $db['hour'] = 0.5;
        }
        $db['user_id'] = $user['id'];
        $db['type'] = $type;
        $db['cover'] = str_replace("https://img.quexiaqp.com", "", $image);


        if ($type == 'qp') {

            $shopOrderModel = new Shoporder();
            $shopOrderModel->where('id', $orderId)->update(['is_comment' => 1]);
            $order = $shopOrderModel->where('id', $orderId)->find();
        } else {
            $shopTableModel = new Shoptableorder();
            $shopTableModel->where('id', $orderId)->update(['is_comment' => 1]);
            $order = $shopTableModel->where('id', $orderId)->find();
        }
        $db['shop_id'] = $order['shop_id'];
        $commentModel->insert($db);
        $this->success('成功');

    }


    public function commentList()
    {

        $user = $this->auth->getUser();
        $commentModel = new Comment();
        $list = $commentModel->with(['shop'])->where('Comment.user_id', $user['id'])->order('valid_time', 'desc')->where('Comment.status', 'undo')->limit(20)->select();

        foreach ($list as $key => $val) {
            $list[$key]['valid_time_txt'] = date('Y-m-d H:i', $val['valid_time']);
        }
        $this->success('', $list);
    }


    public function xuCommentDetail()
    {

        $id = $this->request->param('id');
        $bookModel = new Shoproombook();
        $book = $bookModel->where('id', $id)->find();
        if (!$book) {
            $this->error("此预订不存在，不可续时");
        }

        $shopModel = new Shop();
        $roomModel = new Shoproom();
        $shop = $shopModel->where('id', $book['shop_id'])->find();
        $room = $roomModel->where('id', $book['room_id'])->find();
        $ret = array();
        $ret['book_id'] = $id;
        $ret['shop_name'] = $shop['name'];
        $ret['room_name'] = $room['name'];
        $ret['end_time'] = date("Y-m-d H:i", strtotime("+1 hour", $book['end_time']));


        $this->success('', $ret);

    }


    public function doCommentXu()
    {

        $id = $this->request->param('id');
        $bookModel = new Shoproombook();
        $book = $bookModel->where('id', $id)->find();
        if (!$book) {
            $this->error("此预订不存在，不可续时");
        }
        if ($book['status'] != 'doing') {
            $this->error("此预订状态不可续订");
        }

        $shopOrderModel = new Shoporder();

        $startTime = $book['end_time'];
        $endTime = strtotime("+" . 60 . " minute", $startTime);

        $checkStart = $bookModel->where('room_id', $book['room_id'])->where('start_time', "<=", $startTime)->where("end_time", ">=", $endTime)->find();
        $checkEnd = $bookModel->where('room_id', $book['room_id'])->where('start_time', "<=", $endTime)->where("end_time", ">=", $endTime)->find();

        if ($checkStart != null || $checkEnd != null) {

            if ($checkStart['id'] != $id || $checkEnd['id'] == $id) {
                $this->error("此时间段预被预定,无法续费");
            }
        }

        $commentModel = new Comment();
//        $comment2 = $commentModel->where('order_id', $book['order_id'])->find();
//        if ($comment2) {
//            $this->error("此订单已使用了续时券，不可再用");
//        }

        //判断订单是否已经用过续时券
        $order = $shopOrderModel->where('id', $book['order_id'])->find();
        if ($order['comment_id'] > 0) {
            $this->error("此订单已使用了续时券，不可再用");
        }

        $comment = $commentModel->where('user_id', $book['user_id'])->where('shop_id', $book['shop_id'])->where('status', 'undo')->where('type', 'qp')->order('valid_time', ">", time())->find();
        if (!$comment) {
            $this->error("没有可用的好评券");
        }

        $commentModel->where('id', $comment['id'])->update(['status' => 'done']);
        $orderNo = getOrderSn();
        //修改订单的时间
        if ($order['orgin_order_no'] == '') {
            $shopOrderModel->where('id', $book['order_id'])->update(['book_end' => $endTime, 'orgin_order_no' => $order['order_no'], 'order_no' => $orderNo, 'comment_id' => $comment['id']]);
        } else {
            $shopOrderModel->where('id', $book['order_id'])->update(['book_end' => $endTime, 'order_no' => $orderNo, 'comment_id' => $comment['id']]);
        }
        //修改预订的时间
        $bookModel->where('id', $book['id'])->update(['end_time' => $endTime]);
        //修改保洁的时间
        $bookModel->where('order_id', $book['order_id'])->update(['end_time' => $endTime]);
        //发送续时指令
        $book = $bookModel->where('id', $book['id'])->find();
        $deviceService = new DeviceService();
        $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);

        $this->success('', $orderNo);


    }


    public function xuTableCommentDetail()
    {

        $id = $this->request->param('id');

        $shopTableOrderModel = new Shoptableorder();
        $tableOrder = $shopTableOrderModel->where('id', $id)->find();
        if ($tableOrder['status'] != 'doing') $this->error("此订单状态不可续时");

        $ret = array();
        $ret['id'] = $id;
        $ret['shop_name'] = $tableOrder['shop_name'];
        $ret['room_name'] = $tableOrder['table_name'];
        $ret['end_time'] = date("Y-m-d H:i", strtotime("+30 minute", $tableOrder['book_end']));

        $this->success('', $ret);

    }

    public function doTableCommentXu()
    {

        $id = $this->request->param('id');
        $shopTableOrderModel = new Shoptableorder();
        $tableOrder = $shopTableOrderModel->where('id', $id)->find();
        if ($tableOrder['status'] != 'doing') $this->error("此订单状态不可续时");

        $commentModel = new Comment();
        $comment = $commentModel->where('user_id', $tableOrder['user_id'])->where('shop_id', $tableOrder['shop_id'])->where('status', 'undo')->where('type', 'tq')->order('valid_time', ">", time())->find();
        if (!$comment) {
            $this->error("没有可用的好评券");
        }
        $commentModel->where('id', $comment['id'])->update(['status' => 'done']);
        $end = date("Y-m-d H:i", strtotime("+30 minute", $tableOrder['book_end']));
        $shopTableOrderModel->where('id', $id)->update(['book_end' => $end, 'comment_id' => $comment['id'], 'min' => $tableOrder['min'] + 30]);


        $tableService = new TableService();
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $tableOrder['shop_id'])->where('room_id', $tableOrder['table_id'])->where('device_type', 'tq')->find();
        $tableService->open($tableOrder, $device);


        $this->success('', $tableOrder['order_no']);
    }


    public function refundV3()
    {

        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] != "payed") {
            $this->error("此订单状态不允许退款");
        }

        $time = strtotime("+1 hour", time());
        $fiveMintue = strtotime("-5 minute", time());
        $sixMintue = time() - 6 * 60;
        if ($order['book_start'] < $sixMintue) {
            $this->error('超过了可退款时间，请联系商家退款');
        }

        $amount = $order['amount'];

        $shopModel = new \app\admin\model\Shop();

        $shop = $shopModel->where('id', $order['shop_id'])->find();
        $isRefundAll = 0;//是否退15%
        if ($order['balance'] >= $amount) {
            $refundAmount = 0;
        } else {
            $refundAmount = $amount - $order['balance'];
            if ($order['create_time'] >= $fiveMintue) {
                $refundAmount = $refundAmount;
            } else {
                if ($time >= $order['book_start']) {
                    $isRefundAll = $refundAmount * 0.15 * 100;
                    $isRefundAll = ceil($isRefundAll) / 100;
                    $refundAmount = $refundAmount - $isRefundAll;
                }
            }

        }

        //退实付金额
        if ($order['pay_amount'] > 0 && $refundAmount > 0) {

            $refundOrder_no = getOrderSn();

            $orgModel = new Org();
            $org = $orgModel->where('id', $order['org_id'])->find();
            $mno = $org['mno'];

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
            if ($shopMno && $shopMno['ratio'] == 100) {
                $mno = $shopMno['mno'];
            }

            $req = array();
            $req['mno'] = $mno;
            $req['ordNo'] = $refundOrder_no;
            $req['origOrderNo'] = $order['order_no'];
            $req['amt'] = $refundAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);

            error_log(json_encode($req) . "===v2 refund==" . $ret);
            $result = json_decode($ret, true);

            if ($result['respData']['bizCode'] != "0000") {
                $this->error($result['respData']['bizMsg']);
            }
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'refund_order_no' => $refundOrder_no, 'update_time' => time()]);
        } else {
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);
        }

        //退余额
        if ($order['balance'] > 0) {
            $userBalanceModel = new Userbalance();
            $balanceDb = $userBalanceModel->where('user_id', $order['user_id'])->where('order_id', $order['id'])->where('type', 'out')->find();
            $b = $balanceDb['amount'];
            $percentProfit = 0;
            if ($time >= $order['book_start']) {
                $b = $balanceDb['amount'] - $balanceDb['amount'] * 0.15;
            }
            $userBalanceModel->insert(['user_id' => $balanceDb['user_id'], 'type' => 'in', 'amount' => $b, 'mark' => '订单退款', 'create_time' => time(),
                'shop_id' => $balanceDb['shop_id'], 'order_id' => $balanceDb['order_id'], 'b_type' => 'refund']);

            $userAllBalanceModel = new Userallbalance();
            $allBalanceList = $userAllBalanceModel->where('order_type', 'qp')->where('order_id', $order['id'])->where('type', 'out')->select();

            if (count($allBalanceList) != 0) {
                if ($time >= $order['book_start']) {

                    foreach ($allBalanceList as $key => $val) {
                        $b = $val['amount'] - $val['amount'] * 0.15;
                        $percentProfit += $val['amount'] * 0.15 / $val['ratio'];
                        if ($b > 0) {
                            $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'in', 'amount' => $b, 'create_time' => time(), 'from' => 'refund', 'order_id' => $order['id'], 'order_type' => 'qp']);
                        }
                    }
                    //扣除15%
                } else {
                    foreach ($allBalanceList as $key => $val) {
                        if ($val['amount'] > 0) {
                            $userAllBalanceModel->insert(['ratio' => $val['ratio'], 'user_id' => $order['user_id'], 'type' => 'in', 'amount' => $val['amount'], 'create_time' => time(), 'from' => 'refund', 'order_id' => $order['id'], 'order_type' => 'qp']);
                        }
                    }
                }
                $shopBalanceModel = new Shopbalanceprofit();
                $shopBalanceModel->where('order_id', $order['id'])->delete();
                if ($percentProfit > 0) {
                    $percentProfit = $percentProfit - $percentProfit * 0.006 - $percentProfit * $shop['ratio'] / 100;
                    $shopB = $shopBalanceModel->where('order_id', $order['id'])->find();
                    if ($shopB) {
                        $shopBalanceModel->where('id', $shopB['id'])->update(['amount' => $percentProfit]);
                    } else {
                        $shopBalanceModel->insert(['shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'amount' => $percentProfit, 'create_time' => time(), 'order_type' => 'qp']);
                    }
                } else {
                    $shopBalanceModel->where('order_id', $order['id'])->delete();

                }
            }

        }

        //退商家分润 ，代理商分润
        $userOrderProfitModel = new Userorderprofit();
        if ($order['pay_amount'] > 0) {
            $shopOrderProfitModel = new Shoporderprofit();
            if ($isRefundAll > 0) {
                $orderProfit = $shopOrderProfitModel->where('order_id', $order['id'])->where('user_id', $shop['user_id'])->find();
                if ($orderProfit) {
                    // 计算手续费
                    $public_service = $isRefundAll * 0.006;
                    $shop_service = $isRefundAll * $shop['ratio'] / 100;
                    $service = ceil(($public_service + $shop_service) * 100) / 100;

                    //重新计算收益
                    $profit = $isRefundAll - $service;
                    $shopOrderProfitModel->where('id', $orderProfit['id'])->update(['amount' => $profit]);
                }
            } else {
                $shopOrderProfitModel->where('order_id', $order['id'])->where('user_id', $shop['user_id'])->delete();

            }

            $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->delete();
        }

        //团购券
        if ($order['tuan_id'] != -1) {
            $userTuanModel = new Usertuan();
            $userTuanModel->where('order_id', $order['id'])->update(['status' => 'unuse']);
        }

        //退美团预定q_shop_mt_dy_profit
        $shopMtDouModel = new Shopmtdyprofit();
        if ($order['mt_code'] != '') {
            $shopMtDouModel->where('order_id', $order['id'])->where('order_type', 'qp')->delete();
            if ($shop['agent_ratio'] > 0) {
                $userOrderProfitModel->where('order_id', $order['id'])->where('type', 'order')->delete();
            }
        }

        //退抖音预定q_shop_mt_dy_profit
        if ($order['dou_code'] != '') {
            $shopMtDouModel->where('order_id', $order['id'])->where('order_type', 'qp')->delete();
            if ($shop['agent_ratio'] > 0) {
                $userOrderProfitModel->where('order_id', $order['id'])->where('type', 'order')->delete();
            }
        }

        //恢复预定
        $roomBookOrderModel = new Shoproombook();
        $roomBookOrderModel->where('order_id', $order['id'])->delete();

        $cleanRoomModel = new Roomclean();
        $cleanRoomModel->where('order_id', $order['id'])->delete();

        $mobile = $shop['mobile'];
        $mpwxModel = new Userweixinmp();
        $mp = $mpwxModel->where('mobile', $mobile)->find();
        if ($mp) {

            $userModel = new \app\admin\model\User();
            $user = $userModel->where('id', $order['user_id'])->find();
            $mpService = new MpService();
            $param = array();
            $param['order_no'] = $order['order_no'];
            $param['shop_name'] = $order['shop_name'];
            $param['room_name'] = $order['room_name'];
            $param['mobile'] = $user['mobile'];
            $param['book_start'] = date("Y-m-d H:i", $order['book_start']);

            $mpService->addRefundOrderNotify($param);
        }

        $this->success('退款成功');


    }

    public function checkOrderTip()
    {


        $room_id = $this->request->param('id');
        $hour = $this->request->param('hour');


        $bookStart = "";
        $bookEnd = "";
        $startTime = "";
        $endTime = "";
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('room_id', $room_id)->where('status', 'in', ['undo', 'doing'])->where('start_time', ">", time())->order('start_time', 'asc')->select();
        //$this->success('',$bookList);
        if (count($bookList) > 0) {

            if ($startTime == "") {
                $startTime = strtotime("+10 minute", $bookList[0]['end_time']);
                $endTime = strtotime("+" . $hour . " hour", $startTime);
            }

            foreach ($bookList as $key => $val) {


                if ($key + 1 <= count($bookList) && $key > 0) {

                    //error_log($key."=====for=======".date("Y-m-d H:i",$startTime)."==dddddd222====".date("Y-m-d H:i",$endTime));
                    //error_log($key."=====for=2222======".date("Y-m-d H:i",$val['end_time'])."==dddddd222====".date("Y-m-d H:i", $bookList[$key+1]['start_time']));

                    if ($startTime > $bookList[$key - 1]['end_time'] && $endTime < $val['start_time']) {
                        $bookStart = $startTime;
                        $bookEnd = $endTime;
                        break;
                    } else {
                        $startTime = strtotime("+10 minute", $val['end_time']);
                        $endTime = strtotime("+" . $hour . " hour", $startTime);
                    }


                }
                if (($key + 1) == count($bookList) && count($bookList) == 1) {
                    $bookStart = $startTime;
                    $bookEnd = $endTime;
                }


            }

            if ($bookStart == '') {

                error_log("====bookStart is null==");
                $bookStart = strtotime("+10 minute", $bookList[count($bookList) - 1]['end_time']);
                $bookEnd = strtotime("+" . $hour . " hour", $bookStart);
            }


        }


        error_log($bookStart . "====time===" . $bookStart);
        $ret = array();
        $ret['date'] = date("Y-m-d", $bookStart);
        $ret['startTime'] = date("H:i", $bookStart);
        $ret['endTime'] = date("H:i", $bookEnd);

        $this->success('', $ret);

    }


    public function checkOrderTipTest()
    {

        $room_id = $this->request->param('id');
        $hour = $this->request->param('hour');


        $bookStart = "";
        $bookEnd = "";
        $startTime = "";
        $endTime = "";
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('room_id', $room_id)->where('status', 'in', ['done', 'doing', 'undo'])->where('start_time', ">", '1742049000')->order('start_time', 'asc')->select();


        $this->success('', $bookList);
        //$bookList = $shopRoomBookModel->where('room_id',$room_id)->where('status','in',['undo','doing'])->where('start_time',">",time())->order('start_time','asc')->select();

        if (count($bookList) > 0) {
            if ($startTime == "") {
                $startTime = strtotime("+10 minute", $bookList[0]['end_time']);
                $endTime = strtotime("+" . $hour . " hour", $startTime);
            }
            foreach ($bookList as $key => $val) {


                if ($key + 1 <= count($bookList) && $key > 0) {

                    //error_log($key."=====for=======".date("Y-m-d H:i",$startTime)."==dddddd222====".date("Y-m-d H:i",$endTime));
                    //error_log($key."=====for=2222======".date("Y-m-d H:i",$val['end_time'])."==dddddd222====".date("Y-m-d H:i", $bookList[$key+1]['start_time']));

                    if ($startTime > $bookList[$key - 1]['end_time'] && $endTime < $val['start_time']) {
                        $bookStart = $startTime;
                        $bookEnd = $endTime;
                        break;
                    } else {
                        $startTime = strtotime("+10 minute", $val['end_time']);
                        $endTime = strtotime("+" . $hour . " hour", $startTime);
                    }


                }
                if (($key + 1) == count($bookList) && count($bookList) == 1) {
                    $bookStart = $startTime;
                    $bookEnd = $endTime;
                }


            }

            if ($bookStart == '') {

                error_log("====bookStart is null==");
                $bookStart = strtotime("+10 minute", $bookList[count($bookList) - 1]['end_time']);
                $bookEnd = strtotime("+" . $hour . " hour", $bookStart);
            }


        }


        error_log($bookStart . "====time===" . $bookStart);
        $ret = array();
        $ret['date'] = date("Y-m-d", $bookStart);
        $ret['startTime'] = date("H:i", $bookStart);
        $ret['endTime'] = date("H:i", $bookEnd);

        $this->success('', $ret);

    }

    protected function checkUseTime($bookSt, $bookEt, $useTime)
    {
        list($useSt, $useEt) = explode('~', $useTime);
        $date = date('Y-m-d', $bookSt);
        $z = strtotime($date . " 23:59:59");//判断每天最大时间节点

        $use_st = strtotime($date . " " . $useSt);
        $use_et = strtotime($date . " " . $useEt);
        if ($use_st > $use_et) {
            if ($bookEt <= $z) {
                if ($use_st <= $bookSt) {
                    $use_et += 86400;
                } else {
                    $use_st -= 86400;
                }
            } else {
                $use_et += 86400;
            }
        }
        if ($bookSt >= $use_st && $bookEt <= $use_et) {
            return true;
        }
        return false;
    }

    protected function isOverlap($start1, $end1, $start2, $end2): bool
    {
        if ($end1 < $start2 || $start1 > $end2) {
            return false;
        }
        return true;
    }

}
